0

这是我的代码:

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) 
    } 
}

然而,按钮占据了 300 的整个宽度

4

2 回答 2

0

您正在插入具有定义框架的子层,并将其插入到您的按钮中。所以 sizetofit 正在工作,它的大小等于按钮中的最大层,由于渐变层的大小,它是 300。

于 2016-11-09T10:37:18.870 回答
0

如果您使用多个不同的标题UIControlState,请确保UIControlState在询问之前更改sizeToFit

在我的文章UIButton中,我不得不使用多个标题,一个用于状态,UIControlState.normal另一个用于.selected状态,我期待状态的结果.normal,但按钮处于.selected状态。

于 2018-08-06T08:29:48.897 回答