Search code examples
swiftuibuttonsizeframecustom-button

Why can't I set custom UIButton to the size I want?


I set up a button but the button can't become the size I want, I don't understand why, please help me thanks

attach my code here

var confirmButton : UIButton = {
    let confirmButton = UIButton(type: .custom)
    confirmButton.backgroundColor = .red
    confirmButton.setTitle("確認", for: .normal)
    confirmButton.setTitleColor(.white, for: .normal)
    confirmButton.frame = CGRect(x: 20, y: 20, width: 2000, height: 30)

    return confirmButton
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    confirmButton.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(confirmButton)
    NSLayoutConstraint.activate([
        //confirmButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
        //confirmButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 100),
    ])
}

view hierarchy


Solution

  • it is probably happening because you're setting translatesAutoresizingMaskIntoConstraints as false but not giving any additional constraints. Also, it is cancelling the frame configuration because you've set translatesAutoresizingMaskIntoConstraints.

    Try removing translatesAutoresizingMaskIntoConstraints, by default it is true, and see what happens.