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
答案 0 :(得分:0)
您正在插入具有已定义框架的子图层,并将其插入按钮中。所以sizetofit正在工作它的大小等于按钮中最大的层数,由于梯度层的大小,它是300.
答案 1 :(得分:0)
如果您为不同的UIControlState
使用多个标题,请确保在请求UIControlState
之前先更改sizeToFit
。
在我的UIButton
中,我不得不使用多个标题,一个标题用于UIControlState.normal
,另一个标题用于.selected
状态,我期望使用.normal
状态的结果,但是该按钮处于.selected
状态。