使用UITableViewCell中的约束更改UIButton的宽度

时间:2018-12-17 11:00:48

标签: ios autolayout

我在tableViewCell中有一个按钮,但是我不能缩小它以适合其titleLabel,它小于按钮。该按钮似乎有最小边框。当删除单元格中的所有约束时,可以再次更改其大小。但是在受到这些限制的同时,我应该如何缩小它呢?

单元格中的按钮-“ subjectButton”

enter image description here

“ subjectButton”的约束:

enter image description here

我的尝试

func setButtonStyle(_ button: UIButton, subject: String) {
    button.backgroundColor = UIColor.lightGray
    button.setTitle(subject, for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
    button.layer.cornerRadius = 3
    button.titleLabel?.sizeToFit()
    button.sizeToFit()
    button.frame.size = CGSize(width: 5, height: 20)
}

模拟器(启用了“彩色混合层”):

enter image description here

如您所见,通过使用button.sizeToFit,按钮不会缩小以适合其titleLabel。另外,我无法使用button.frame.size = CGSize(width: 5, height: 20)来手动调整其大小。

为什么?预先感谢。

2 个答案:

答案 0 :(得分:0)

创建类似@Property IBOutlet的内容

@property (nonatomic,strong) IBOutlet NSLayoutConstraint *height;

将高度更改为

self.height.constant = button.frame.size.height + 15;

答案 1 :(得分:0)

已解决。

button.widthAnchor.constraint(equalToConstant: button.titleLabel?.frame.width ?? 0).isActive = true
相关问题