Advertisement
nferocious76

Programmatically Setting Layout

Nov 2nd, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5.  
  6. class CustomView: UIView {
  7.  
  8. var titleLabel: UILabel!
  9. var messageLabel: UILabel!
  10.  
  11. override init(frame: CGRect) {
  12. super.init(frame: frame)
  13. }
  14.  
  15. required init?(coder aDecoder: NSCoder) {
  16. super.init(coder: aDecoder)
  17. }
  18.  
  19. override func awakeFromNib() {
  20. super.awakeFromNib()
  21.  
  22. layoutLabels()
  23.  
  24. }
  25.  
  26. func layoutLabels() {
  27.  
  28. let tFrame = CGRect(x: 10, y: 10, width: frame.width - 20, height: 40)
  29. titleLabel = UILabel(frame: tFrame)
  30. addSubview(titleLabel)
  31.  
  32.  
  33. let mFrame = CGRect(x: 10, y: 60, width: frame.width - 20, height: 40)
  34. messageLabel = UILabel(frame: mFrame)
  35. addSubview(messageLabel)
  36.  
  37. // add constraints programmatically
  38.  
  39. let tLead = NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
  40. let tTop = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10)
  41. let tTrail = NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
  42. addConstraints([tLead, tTop, tTrail])
  43.  
  44. let tHeight = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
  45. titleLabel.addConstraint(tHeight)
  46.  
  47. let mLead = NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
  48. let mTop = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 10)
  49. let mTrail = NSLayoutConstraint(item: messageLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
  50. addConstraints([mLead, mTop, mTrail])
  51.  
  52. let mHeight = NSLayoutConstraint(item: messageLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
  53. messageLabel.addConstraint(mHeight)
  54.  
  55. titleLabel.backgroundColor = .green
  56. messageLabel.backgroundColor = .red
  57.  
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement