I am trying to add a button pragmatically to a UIView. This code will work with a UI label, but when using it with a button, the constraints fail. How can I make this work? Thanks.
let homeButton = UIButton(frame: CGRectZero)
homeButton.setTitle("Home", forState: .Normal)
homeButton.titleLabel!.textAlignment = NSTextAlignment.Center
homeButton.titleLabel!.textColor = UIColor.whiteColor()
homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(homeButton)
let buttonWidthConstraint = NSLayoutConstraint(item: homeButton, attribute: .Width, relatedBy: .Equal, toItem: self.containerView, attribute: .Width, multiplier: 0.5, constant: 0)
containerView.addConstraint(buttonWidthConstraint)
let buttonHeightConstraint = NSLayoutConstraint(item: homeButton, attribute: .Height, relatedBy: .Equal, toItem: self.containerView, attribute: .Height, multiplier: 0.5,constant: 0)
containerView.addConstraint(buttonHeightConstraint)
let buttonXConstraint = NSLayoutConstraint(item: homeButton, attribute: .CenterX, relatedBy: .Equal, toItem: self.containerView, attribute: .CenterX, multiplier: 1, constant: 0)
let buttonYConstraint = NSLayoutConstraint(item: homeButton, attribute: .CenterY, relatedBy: .Equal, toItem: self.containerView, attribute: .CenterY, multiplier: 1, constant: 0)
containerView.addConstraint(buttonXConstraint)
containerView.addConstraint(buttonYConstraint)
you should use homeButton.translatesAutoresizingMaskIntoConstraints = false instead of homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false.
because you should disable autoresizingmask for button not for button's titleLabel!!!
Hope this will help :)
Related
I am unable to understand where to add subview so that the button can lie in middle of the existing views.
This is work for me. (swift 4.0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let yourView = self.view
addButtonOnCentral(yourView!)
}
func addButtonOnCentral(_ view:UIView) {
let btn = UIButton.init()
btn.backgroundColor = UIColor.yellow
btn.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(btn)
let widthConstraint = NSLayoutConstraint(item: btn, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20)
let heightConstraint = NSLayoutConstraint(item: btn, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30)
let xConstraint = NSLayoutConstraint(item: btn, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: btn, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])
}
I am trying to autolayout 3 UI elements in the order which I present in the image. A UITextfield, UIDatePicker and a UIButton in a UIView.
I am avoiding to use storyboard as I want to get a better understanding of programmatic constraints and eventually use animations for them.
So far I have got this with some constraints I have tried:
and here is the code for the one I am working on:
override func viewDidLoad() {
super.viewDidLoad()
picker.translatesAutoresizingMaskIntoConstraints = false
picker.backgroundColor = UIColor.red
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.blue
button.setTitle("Button", for: .normal)
self.view.addSubview(picker)
self.view.addSubview(button)
let PickercenterX = NSLayoutConstraint(item: self.picker, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let PickercenterBottom = NSLayoutConstraint(item: self.picker, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.button, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -30)
let Pickerheight = NSLayoutConstraint(item: self.picker, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 150)
let Pickerwidth = NSLayoutConstraint(item: self.picker, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -5)
// Centers it on the x axis. Pushes it it right if co constant has a value > 0
let centerX = NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let centerBottom = NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -15)
let height = NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
let width = NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -15)
self.view.addConstraints([centerX, centerBottom, height, width, PickercenterX, PickercenterBottom, Pickerheight, Pickerwidth])
}
I am trying to work the button and date picker first before moving onto the textfield. How can I achieve this programmatically ?
Here lies the problem:-
You were setting the picker bottom to be equal to the button bottom with constant -30, although I know what were you trying to do, you were trying to give vertical space between picker and button. So it should be linked like, picker's bottom equal to button's top with constant -30.
Moreover you are missing out on activating the constraints by not adding isActive in the end.
Another way to activate all constraints at once is by using NSLayoutConstraint.activate() method
let PickercenterBottom = NSLayoutConstraint(item: self.picker, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.button, attribute: NSLayoutAttribute.top, multiplier: 1, constant: -30).isActive = true
I know this is a hard problem to debug. I will try to explain, you can ask question from comments section.
I want to use message bubbles in my app. I wrote some code for constraints, but it is not working well.
How can i put the left edge of blue bubble to red line?
Here is my code:
When tableview cell loads this method is running:
private func setup() {
bubbleImageView = UIImageView(image: bubbleImage.incoming, highlightedImage: bubbleImage.incomingHighlighed)
bubbleImageView.userInteractionEnabled = true
messageLabel = UILabel(frame: CGRectZero)
messageLabel.font = UIFont.systemFontOfSize(15)
messageLabel.numberOfLines = 0
messageLabel.userInteractionEnabled = true
selectionStyle = .None
contentView.addSubview(bubbleImageView)
bubbleImageView.addSubview(messageLabel)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
bubbleImageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: bubbleImageView, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 10))
contentView.addConstraint(NSLayoutConstraint(item: bubbleImageView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 4.5))
bubbleImageView.addConstraint(NSLayoutConstraint(item: bubbleImageView, attribute: .Width, relatedBy: .Equal, toItem: messageLabel, attribute: .Width, multiplier: 1, constant: 30))
contentView.addConstraint(NSLayoutConstraint(item: bubbleImageView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -4.5))
bubbleImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterX, relatedBy: .Equal, toItem: bubbleImageView, attribute: .CenterX, multiplier: 1, constant: -2))
bubbleImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: bubbleImageView, attribute: .CenterY, multiplier: 1, constant: -0.5))
messageLabel.preferredMaxLayoutWidth = 218
bubbleImageView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Height, relatedBy: .Equal, toItem: bubbleImageView, attribute: .Height, multiplier: 1, constant: -15))
}
As you can see i am creating bubble background and label for text.
And second method:
func setCell(message:Message) {
messageLabel.text="testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"
var layoutAttribute: NSLayoutAttribute
var layoutConstant: CGFloat
if message.incoming {
bubbleImageView.image=bgImage.incoming
messageLabel.textColor = UIColor.blackColor()
layoutAttribute = .Left
layoutConstant = 10
}else{
if message.isSent == 1 {
bubbleImageView.image = bgImage.outgoing
}
if message.isSent == 0 {
bubbleImageView.image = bgImage.notYetSent
}
messageLabel.textColor = UIColor.whiteColor()
layoutAttribute = .Right
layoutConstant = -10
}
contentView.addConstraint(NSLayoutConstraint(item: bubbleImageView, attribute: layoutAttribute, relatedBy: .Equal, toItem: contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))
}
What is the problem with my code? It is working well for incoming messages (gray bubble) and not working well for outgoing messages (blue bubble)
I get it. You have to add a constraint that doesnt allows the bubble to exceed the max width. So you have to add a constraint like that:
let widthConstraint = NSLayoutConstraint(item: youritem, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.LessThanOrEqual,
toItem: self.youItem.superview, attribute: NSLayoutAttribute.Width,
multiplier: 1.0, constant: 100)
The Following are the constraints that am using.
<NSLayoutConstraint:0x7fcfdd405bc0 UILabel:0x7fcfdd405780'ACTIVITY'.centerY == UIView:0x7fcfdb677b60.centerY>The view hierarchy is not prepared for the constraint:
footer!.frame = CGRectMake(0, 0, tableView.frame.size.width, FOOTER_HEIGHT)
let activityLabel = UILabel()
activityLabel.text = "SomeText"
activityLabel.translatesAutoresizingMaskIntoConstraints = false
let CenterConstraint = NSLayoutConstraint(item: activityLabel, attribute: .CenterX, relatedBy: .Equal, toItem: footerView, attribute: .CenterX, multiplier: 1, constant: 0)
let CenterConstraint = NSLayoutConstraint(item: activityLabel, attribute: .CenterY, relatedBy: .Equal, toItem: footerView, attribute: .CenterY, multiplier: 1, constant: 0)
footer!.addConstraints([xxCenterConstraint,yyCenterConstraint])
footer!.addSubview(activityLabel)
let notificationLabel = UILabel()
notificationLabel.text = "9"
notificationLabel.textAlignment = .Center
notificationLabel.backgroundColor = customBlueColor
footerView!.addSubview(notificationLabel)
notificationLabel.translatesAutoresizingMaskIntoConstraints = false
let width = NSLayoutConstraint(item: notificationLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: NOTIFICATION_LABEL_HEIGHT)
let height = NSLayoutConstraint(item: notificationLabel, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: NOTIFICATION_LABEL_HEIGHT)
let yCenterConstraint = NSLayoutConstraint(item: notificationLabel, attribute: .CenterY, relatedBy: .Equal, toItem: footerView, attribute: .CenterY, multiplier: 1, constant: 0)
let leadingConstraint1 = NSLayoutConstraint(item: activityLabel, attribute: .Trailing, relatedBy: .Equal, toItem: notificationLabel, attribute: .Leading, multiplier: 1, constant:-LEADING_SPACE)
footer!.addConstraints([width,height,yCenterConstraint,leadingConstraint1])
notificationLabel.layer.cornerRadius = NOTIFICATION_LABEL_HEIGHT/2
notificationLabel.clipsToBounds = true
You can't add constraints before the views are part of the same view hierarchy. Move the addSubview line before the addConstraints line.
I am attempting to reproduce the constraints in this screenshot, which are applied to a static UITableViewCell:
Here is the code I'm using to try to do this:
#IBOutlet weak var cellTest: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
cellTest.backgroundColor = UIColor.yellowColor()
let vw = UIView()
vw.backgroundColor = UIColor.greenColor()
cellTest.contentView.addSubview(vw)
cellTest.contentView.translatesAutoresizingMaskIntoConstraints = false
vw.translatesAutoresizingMaskIntoConstraints = false
let constraintWidth = NSLayoutConstraint(item: vw, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 400)
let constraintHeight = NSLayoutConstraint(item: vw, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 150)
let constraintCentreX = NSLayoutConstraint(item: vw, attribute: .CenterX, relatedBy: .Equal, toItem: vw.superview!, attribute: .CenterX, multiplier: 1, constant: 0)
let constraintCentreY = NSLayoutConstraint(item: vw, attribute: .CenterY, relatedBy: .Equal, toItem: vw.superview!, attribute: .CenterY, multiplier: 1, constant: 0)
cellTest.contentView.addConstraints([constraintWidth, constraintHeight, constraintCentreX, constraintCentreY ])
}
However, below is the unexpected output, with the view in the top left instead of centred. Any help is much appreciated as I've spent quite some time trying to figure this out:
I needed to add constraints to the cell's contentView, as well. These are added to the cell itself.
Code and screenshot below.
#IBOutlet weak var cellTest: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
cellTest.backgroundColor = UIColor.yellowColor()
let vw = UIView()
vw.backgroundColor = UIColor.greenColor()
cellTest.contentView.addSubview(vw)
cellTest.contentView.translatesAutoresizingMaskIntoConstraints = false
vw.translatesAutoresizingMaskIntoConstraints = false
let bottomConstraint = NSLayoutConstraint(item: cellTest.contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cellTest.contentView.superview!, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: cellTest.contentView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: cellTest.contentView.superview!, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: cellTest.contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: cellTest.contentView.superview!, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: cellTest.contentView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: cellTest.contentView.superview!, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
cellTest.addConstraints([bottomConstraint, trailingConstraint, topConstraint, leadingConstraint])
let constraintWidth = NSLayoutConstraint(item: vw, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200)
constraintWidth.priority = 1000
let constraintHeight = NSLayoutConstraint(item: vw, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 80)
constraintHeight.priority = 1000
let constraintCentreX = NSLayoutConstraint(item: vw, attribute: .CenterX, relatedBy: .Equal, toItem: vw.superview!, attribute: .CenterX, multiplier: 1, constant: 0)
constraintCentreX.priority = 1000
let constraintCentreY = NSLayoutConstraint(item: vw, attribute: .CenterY, relatedBy: .Equal, toItem: vw.superview!, attribute: .CenterY, multiplier: 1, constant: 0)
constraintCentreY.priority = 1000
cellTest.contentView.addConstraints([constraintWidth, constraintHeight, constraintCentreX, constraintCentreY ])
}