UIButton sizeToFit not working

1.8k views Asked by At

This is my code :

let button_video = UIButton(type: .custom)
button_video.frame = CGRect.zero
if subsession.VideoUrl != nil
{   
    button_video.frame = CGRect(x: 10, y: yAxis + 15, width: 300, height: 30)
    button_video.contentEdgeInsets = UIEdgeInsets(top: 3, left: 28, bottom: 7, right: 5)
    if iVideoNumber == 0
    {
        button_video.setTitle(String(format: "Video #%i", 1), for: .normal)
    }
    else
    {
        button_video.setTitle(String(format: "Video #%i", iVideoNumber+1), for: .normal)
        }
        button_video.titleLabel?.font = UIFont(name: "OpenSans-Regular", size: 15)
        button_video.titleLabel?.textColor = UIColor.white
        button_video.setTitleColor(UIColor.white, for: .normal)
        button_video.titleLabel?.numberOfLines = 0
        button_video.titleLabel?.lineBreakMode = .byWordWrapping
        button_video.titleLabel?.textAlignment = .center
        button_video.tag = iCount
        button_video.addTarget(self, action: #selector(CourseDetailViewController.loadVideo(sender:)), for: .touchUpInside)
        let btnGradient = CAGradientLayer()
        btnGradient.frame = button_video.bounds
        btnGradient.cornerRadius = 6
        btnGradient.colors = [(UIColor(red: 174.0 / 255.0, green: 127.0 / 255.0, blue: 183.0 / 255.0, alpha: 1.0).cgColor as CGColor), (UIColor(red: 78.0 / 255.0, green: 57.0 / 255.0, blue: 96.0 / 255.0, alpha: 1.0).cgColor as CGColor)]
        button_video.layer.insertSublayer(btnGradient, at: 0)
        button_video.sizeToFit()
        view_scrollView.addSubview(button_video) 
    } 
}

The button however occupies the whole width of 300

2

There are 2 answers

0
PlusInfosys On

You are inserting sublayer with defined frame, and inserting it in your button. So sizetofit is working its size is equal to largest layes in button which is 300 due to size of gradient layer.

0
AamirR On

If you are using multiple titles for different UIControlState, make sure to change the UIControlState before asking for sizeToFit.

In my UIButton I had to use multiple titles, one for UIControlState.normal and another for .selected state, I was expecting the result of .normal state, but the button was on .selected state.