Swift : Adding Constraints to UILabel Programmatically - swift

So I had a break from iOS dev for 4 months and its seems I have forgotten everything. All I am trying to do is place a Label programmatically at 0,0, size 200,50. I hear there is a few changes in iOS8 which I don't remember
let x : CGFloat = 0.0
let y : CGFloat = 0.0
let width : CGFloat = 200.0
let height : CGFloat = 50.0
self.label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
self.label.text = "SIMON"
self.label.textColor = UIColor.whiteColor()
self.label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 24)
self.label.textAlignment = NSTextAlignment.Center
self.label.backgroundColor = UIColor.redColor()
self.label.layer.masksToBounds = true;
self.label.layer.cornerRadius = 8.0;
self.label.adjustsFontSizeToFitWidth = true;
self.label.translatesAutoresizingMaskIntoConstraints = false
widthConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width)
heightConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: height)
leftConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: x)
topConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: y)
self.view.addSubview(self.label)
NSLayoutConstraint.activateConstraints([leftConstraint,topConstraint, widthConstraint, heightConstraint] )

It appears I was being dump!
It was the event I was calling it from, not the code. Moved to viewWillAppear

Related

Setting 2 label in header programatically - not label seen

I'm trying to set 2 labels, one under other with different font size in the header. The function is called like this:
viewController.navigationItem.titleView = self.setHeader()
And code responsible for generating label is :
private func setHeader(agentName: String = "", isTyping: Bool = false) -> UIView {
let headerLabel: UILabel = {
let label = UILabel()
label.text = self.title
label.font = UIFont.systemFont(ofSize: 21)
label.textColor = UIColor.white
return label
}()
let subheaderLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
return label
}()
let headerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(headerLabel)
view.addConstraints([
NSLayoutConstraint(item: headerLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: headerLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 16),
NSLayoutConstraint(item: headerLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 16)
])
return view
}()
if (!agentName.isEmpty) {
if (isTyping) {
subheaderLabel.text = agentName + " is typing ..."
} else {
subheaderLabel.text = agentName
}
headerView.addSubview(subheaderLabel)
}
return headerView
}
When I running IOS app there is nothing shown in the header. What is a reason?
I think you need to set the frame for the headerView. So in the initialization code for the headerView, use initializer with frame:
let headerView: UIView = {
// initialize the view with frame
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 35))
// you want to call this on the headerLabel, not on view
headerLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(headerLabel)
view.addConstraints([
NSLayoutConstraint(item: headerLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: headerLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 16),
NSLayoutConstraint(item: headerLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 16)
])
return view
}()
Moreover, I believe headerLabel you want to set translatesAutoresizingMaskIntoConstraints on headerLabel rather than on headerView (headerView is positioned through frame and not Autolayout).
Also, notice that you add subheaderLabel to the view, but you never position it, don't forget about it either (although this should cause only subheaderLabel not to be rendered properly).

Centering label and UITextField inside a TableView

New to xcode/swift, spending a couple of days now trying to fix this one. Creating a universal app and having problems getting the constraint working programmatically. I would like to programmatically add a label and a UITextField inside a TableView. The label should always have a fixed width. The text field should have variable width depending on the device.
Here is what is looks like now:
Here is an idea of how it should look:
The label should be a set width. But the textfield should use the available screen.
Here is the code so far:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Setup Cell
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
// Make cell unselectable
cell.selectionStyle = .none
// Process Each Row
let row = indexPath.row
switch row
{
case 0:
let label = UILabel()
label.text = "First Name:"
label.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(40), height: CGFloat(30))
cell.contentView.addSubview(label)
var textField: UITextField = UITextField()
textField.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(170), height: CGFloat(30))
textField.borderStyle = .roundedRect
textField.backgroundColor = UIColor.magenta
textField.text = "TEST"
textField.textColor = UIColor.black
textField.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(textField)
let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: .leftMargin, relatedBy: .equal, toItem: label, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: .rightMargin, relatedBy: .equal, toItem: textField, attribute: .rightMargin, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(leadingConstraint)
cell.contentView.addConstraint(trailingConstraint)
....
Please let me know if you need additional information before a downvote. Any help would be appreciated. Thanks.
Answer by UpholderOfTruth:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Setup Cell
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
// Make cell unselectable
cell.selectionStyle = .none
// Process Each Row
let row = indexPath.row
switch row
{
case 0:
let label = UILabel()
label.text = "First Name:"
label.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(40), height: CGFloat(30))
label.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(label)
var textField: UITextField = UITextField()
textField.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(170), height: CGFloat(30))
textField.borderStyle = .roundedRect
textField.backgroundColor = UIColor.magenta
textField.text = "TEST"
textField.textColor = UIColor.black
textField.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(textField)
// Horizontal Constraints
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[label(==100)][textField]|", options: .init(rawValue: 0), metrics: nil, views: ["label": label, "textField": textField]))
// Vertical Constraints
cell.contentView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0))
cell.contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0))
....
I would suggest go full auto layout and don't mix methods. So first set both view to use auto layout via setting the translatesAutoresizingMaskIntoConstraints to false.
Then either set the constraints visually like this:
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[label(==100)][textField]|", options: .init(rawValue: 0), metrics: nil, views: ["label": label, "textField": textField]))
or with individual constraints like this:
cell.contentView.addConstraint(NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: cell, attribute: .left, multiplier: 1, constant: 0))
cell.contentView.addConstraint(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 100))
cell.contentView.addConstraint(NSLayoutConstraint(item: label, attribute: .right, relatedBy: .equal, toItem: textField, attribute: .left, multiplier: 1, constant: 0))
cell.contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .right, relatedBy: .equal, toItem: cell, attribute: .right, multiplier: 1, constant: 0))
Of course this just handles horiztonal positioning and sizing you need to do something about vertical positioning and sizing as well but you may be setting that up further down in your code.
Edit:
To centre vertically you can do this:
cell.contentView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0))
cell.contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0))
Edit2:
Combining into a single line:
cell.contentView.addConstraints([NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0), NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0)])
Edit3:
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[label(==100)][textField]-8-|", options: .init(rawValue: 0), metrics: nil, views: ["label": label, "textField": textField]))
Change these properties:
switch row
{
case 0:
let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: .leftMargin, relatedBy: .equal, toItem: label, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: .rightMargin, relatedBy: .equal, toItem: textField, attribute: .rightMargin, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(leadingConstraint)
cell.contentView.addConstraint(trailingConstraint)
let label = UILabel()
label.text = "First Name:"
//here is the trick: play with x and width. It might also be cell.contentView.size().width
label.frame = CGRect(x: CGFloat(35), y: CGFloat(0), width: CGFloat(cell.frame.width * 1/3), height: CGFloat(30))
cell.contentView.addSubview(label)
var textField = UITextField()
textField.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(cell.frame.width * 2/3), height: CGFloat(30))
textField.borderStyle = .roundedRect
textField.backgroundColor = UIColor.magenta
textField.text = "TEST TEST TEST"
textField.textColor = UIColor.black
textField.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(textField)
Let me know if this works.

Swift how to animate up the screen while staying centered, but also shrink in size

I want to do a simple animation where the logo moves from point A on the screen at size 1 to point B on the screen at size 2
I found
self.logoOutlet.frame = CGRect(x: x, y: y, width: 115, height: 115)
how do i get it so the x is centered no matter what size the phone is?
You either have to do math, to calculate the value of x based on the bounds of the superview of logoOutlet or use AutoLayout and just use a center X constraint (which is probably the better choice).
You can read about the specifics in the documentation: Auto Layout Guide, or use one of the many tutorials on Auto Layout you can find via Google search.
Through a combination of two different answers I found a solution that works
self.logoOutlet.frame = CGRect(x: self.view.frame.midX, y: 26, width: 115, height: 115)
self.logoOutlet.center.x = self.view.center.x
Here's an example using Auto Layout:
#IBAction func animateLogo(sender: UIButton) {
let newView = UIView()
newView.backgroundColor = .redColor()
newView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(newView)
let topConstraint = NSLayoutConstraint(item: newView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 500.0)
let centerXConstraint = NSLayoutConstraint(item: newView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
let widthConstraint = NSLayoutConstraint(item: newView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200)
let heightConstraint = NSLayoutConstraint(item: newView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200)
NSLayoutConstraint.activateConstraints([topConstraint, centerXConstraint, widthConstraint, heightConstraint])
self.view.layoutIfNeeded()
// Now change the constraint for the second point
widthConstraint.constant = 50
heightConstraint.constant = 50
topConstraint.constant = 50
// Animate the move over 5 seconds
UIView.animateWithDuration(5.0) {
self.view.layoutIfNeeded()
}
}

Generate labels and align in middle

How can i generate a random amount of labels and align them next to each other in the middle?
I have this code to generate an label:
var label = UILabel(frame: CGRectMake(5, 196, 35,45 ))
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = "1";
label.tag = 5;
self.view.addSubview(label);
This work perfect, but how can i generate more than 1 label and set them next to each other in the middle?
like this:
The green things are my labels, and are align horizontally. How can i do this programmatically?
This will do it:
var lastLabel : UILabel?
var count = 1
#IBAction func addlabel(sender: AnyObject) {
var label = UILabel()
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = count.description;
count++
label.tag = 5;
var centerX = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
centerX.priority = 999
//This if you want to center it vertically also
var centerY = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
var height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)
var width = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 45)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(label);
if let prevlabel = lastLabel {
var align = NSLayoutConstraint(item: prevlabel, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -20)
//Here just add the NSLayoutConstraint you want to apply, if its only horizontal then not add centerY
NSLayoutConstraint.activateConstraints([align, centerY, height, width, centerX])
}else {
NSLayoutConstraint.activateConstraints([centerX, centerY, height, width])
}
lastLabel = label
}

Horizontal Align labels [duplicate]

This question already has an answer here:
Generate labels and align in middle
(1 answer)
Closed 7 years ago.
How can i generate a random amount of labels and align them next to each other in the middle?
I have this code to generate an label:
var label = UILabel(frame: CGRectMake(5, 196, 35,45 ))
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = "1";
label.tag = 5;
self.view.addSubview(label);
This work perfect, but how can i generate more than 1 label and set them next to each other in the middle?
like this:
Or if i generate 3 labels it must looks like this:
Is this possible to do it programmaticly?
This will do it:
var lastLabel : UILabel?
var count = 1
#IBAction func addlabel(sender: AnyObject) {
var label = UILabel()
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()
label.text = count.description;
count++
label.tag = 5;
var centerX = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
centerX.priority = 999
//This if you want to center it vertically also
var centerY = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
var height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)
var width = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 45)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(label);
if let prevlabel = lastLabel {
var align = NSLayoutConstraint(item: prevlabel, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -20)
//Here just add the NSLayoutConstraint you want to apply, if its only horizontal then not add centerY
NSLayoutConstraint.activateConstraints([align, centerY, height, width, centerX])
}else {
NSLayoutConstraint.activateConstraints([centerX, centerY, height, width])
}
lastLabel = label
}