Advertisement
nferocious76

Swift NSLayoutConstraint sample

Nov 2nd, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 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. layoutLabels()
  15. }
  16.  
  17. required init?(coder aDecoder: NSCoder) {
  18. super.init(coder: aDecoder)
  19. }
  20.  
  21. override func awakeFromNib() {
  22. super.awakeFromNib()
  23.  
  24. layoutLabels()
  25.  
  26. }
  27.  
  28. func layoutLabels() {
  29.  
  30. let tFrame = CGRect(x: 10, y: 10, width: frame.width - 20, height: 40)
  31. titleLabel = UILabel(frame: tFrame)
  32. addSubview(titleLabel)
  33.  
  34.  
  35. let mFrame = CGRect(x: 10, y: 60, width: frame.width - 20, height: 40)
  36. messageLabel = UILabel(frame: mFrame)
  37. addSubview(messageLabel)
  38.  
  39. // add constraints programmatically
  40.  
  41. let tLead = NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
  42. let tTop = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10)
  43. let tTrail = NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
  44. addConstraints([tLead, tTop, tTrail])
  45.  
  46. let tHeight = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
  47. titleLabel.addConstraint(tHeight)
  48.  
  49. let mLead = NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
  50. let mTop = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 10)
  51. let mTrail = NSLayoutConstraint(item: messageLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
  52. addConstraints([mLead, mTop, mTrail])
  53.  
  54. let mHeight = NSLayoutConstraint(item: messageLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
  55. messageLabel.addConstraint(mHeight)
  56.  
  57. titleLabel.backgroundColor = .green
  58. messageLabel.backgroundColor = .red
  59.  
  60. }
  61. }
  62.  
  63. let this = CustomView(frame: CGRect(x: 0, y: 0, width: 500, height: 200))
  64.  
  65. print(this.subviews)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement