Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import UIKit
- class CustomView: UIView {
- var titleLabel: UILabel!
- var messageLabel: UILabel!
- override init(frame: CGRect) {
- super.init(frame: frame)
- layoutLabels()
- }
- required init?(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- }
- override func awakeFromNib() {
- super.awakeFromNib()
- layoutLabels()
- }
- func layoutLabels() {
- let tFrame = CGRect(x: 10, y: 10, width: frame.width - 20, height: 40)
- titleLabel = UILabel(frame: tFrame)
- addSubview(titleLabel)
- let mFrame = CGRect(x: 10, y: 60, width: frame.width - 20, height: 40)
- messageLabel = UILabel(frame: mFrame)
- addSubview(messageLabel)
- // add constraints programmatically
- let tLead = NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
- let tTop = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10)
- let tTrail = NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
- addConstraints([tLead, tTop, tTrail])
- let tHeight = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
- titleLabel.addConstraint(tHeight)
- let mLead = NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
- let mTop = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 10)
- let mTrail = NSLayoutConstraint(item: messageLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 10)
- addConstraints([mLead, mTop, mTrail])
- let mHeight = NSLayoutConstraint(item: messageLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
- messageLabel.addConstraint(mHeight)
- titleLabel.backgroundColor = .green
- messageLabel.backgroundColor = .red
- }
- }
- let this = CustomView(frame: CGRect(x: 0, y: 0, width: 500, height: 200))
- print(this.subviews)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement