I have a UI made on interface builder, it looks like this:
At the bottom, I must add a UIButton, labeled "reject":
I use the following code and it looks good (also on the simulator):
func createRejectButton(){
let rejectButton = UIButton()
rejectButton.setTitleColor(.red, for: .normal)
rejectButton.setTitle("Reject", for: .normal)
rejectButton.frame = CGRect(x: view.frame.width/2 - 100, y: view.frame.height / 2, width: 200, height: 40)
view.addSubview(rejectButton)
rejectButton.addTarget(self, action: #selector(rejectAction), for: .touchUpInside)
if (self.movement.rejected) {
rejectButton.isHidden = true
} else {
rejectButton.isHidden = false
}
//With the frame definition, I get the UIButton centered, but the Y coordinate is off, so I add a vertical spacing to the accountBalanceLabel
let verticalSpacing1 = NSLayoutConstraint(item: rejectButton, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: accountBalanceLabel, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 15)
NSLayoutConstraint.activate([verticalSpacing1])
}
I have to do the same with a label: this label will appear when the user comes again in the ViewController, after the rejectButton has been pressed:
func createRejectedLabel() {
let rejectedLabel = UILabel()
rejectedLabel.text = "Rejected"
rejectedLabel.textColor = UIColor.red
rejectedLabel.frame = CGRect(x: view.frame.width/2 - 100, y: view.frame.height*3/4, width: 200, height: 40)
self.view.addSubview(rejectedLabel)
if (self.movement.rejected) {
rejectedLabel.isHidden = false
} else {
rejectedLabel.isHidden = true
}
let verticalSpacing1 = NSLayoutConstraint(item: rejectedLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: accountBalanceLAbel, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 15)
NSLayoutConstraint.activate([verticalSpacing1])
}
if I run the app, apart from the fact that I don't get the rejectedLabel to be at the defined verticalSpacing, I get errors on the console regarding the button!
why do I get those errors if the button was working? (if I stop calling the createRegectedLabel() function, I stop getting those errors. This is the message I get:
By the way, I am asked to add the button and the label con code, while leaving untouched the Interface Builder part, so getting rid of it is not an option. Both the button and the label plus the constraints they require must be created in code.