我正在尝试将按钮放置在UITableCell
的最右侧,但是它无法正常工作。我正在使用以下代码。
override func awakeFromNib() {
flagBtn = UIButton(frame: CGRect(x: self.frame.maxX, y: 0, width: 30, height: 20))
contentView.addSubview(flagBtn)
// ...
}
maxX
没有给出完整宽度。
答案 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
}
希望它会对您有所帮助。