John Doe
John Doe

Reputation: 2491

How to position a button to right most edge of UITableCell with a margin programatically?

I am trying to position a button to the right most side of a UITableCell, but it is not working properly. I am using the below code.

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

The maxX is not giving the full width.

pos

Upvotes: 0

Views: 62

Answers (2)

Muhammad Waqas Bhati
Muhammad Waqas Bhati

Reputation: 2805

First declare you UIbutton as a lazy property like below

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

Secondly add your constraint

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
}

Hope it will help you.

Upvotes: 1

kamwysoc
kamwysoc

Reputation: 6859

You can use constraints to achieve this.

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 you can read more about NSLayoutAnchors

Upvotes: 2

Related Questions