如何以编程方式将按钮定位在UITableCell的最右边缘?

时间:2019-04-02 06:59:34

标签: ios swift uitableview uibutton

我正在尝试将按钮放置在UITableCell的最右侧,但是它无法正常工作。我正在使用以下代码。

override func awakeFromNib() {
    flagBtn = UIButton(frame: CGRect(x: self.frame.maxX, y: 0, width: 30, height: 20))
    contentView.addSubview(flagBtn)
    // ...
}

maxX没有给出完整宽度。

pos

2 个答案:

答案 0 :(得分:2)

您可以使用约束来实现此目的。

override func awakeFromNib() {
    flagBtn = UIButton()
    contentView.addSubview(flagBtn)

    flagBtn.translatesAutoresizingMaskIntoConstraints = false
    flagBtn.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
    flagBtn.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    flagBtn.widthAnchor.constraint(equalToConstant: 30).isActive = true
    flagBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true
}

Here,您可以阅读有关NSLayoutAnchors的更多信息

答案 1 :(得分:1)

首先将UIbutton声明为如下所示的惰性属性

lazy var flagBtn: UIButton = {
    let btn = UIButton()
    btn.setTitle("foo", for: .normal)
    btn.backgroundColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
    btn.translatesAutoresizingMaskIntoConstraints = false
    return btn
}()

第二个添加约束

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    contentView.addSubview(flagBtn)

    contentView.topAnchor.constraint(equalTo: flagBtn.topAnchor, constant: 5.0).isActive = true
    contentView.rightAnchor.constraint(equalTo: flagBtn.rightAnchor, constant: 5.0).isActive = true
    flagBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
    flagBtn.widthAnchor.constraint(equalToConstant: 30).isActive = true
}

希望它会对您有所帮助。