Skip to content

Instantly share code, notes, and snippets.

@NickHung1982
Created November 4, 2017 21:32
Show Gist options
  • Save NickHung1982/c3da9b17b9c994acd6c4f38626706152 to your computer and use it in GitHub Desktop.
Save NickHung1982/c3da9b17b9c994acd6c4f38626706152 to your computer and use it in GitHub Desktop.
update with anthor
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//add UIImageView
customImageView = UIImageView()
customImageView.translatesAutoresizingMaskIntoConstraints = false
customImageView.backgroundColor = UIColor.red
self.addSubview(customImageView)
//add UILabel
customLabel = UILabel()
customLabel.numberOfLines = 1
customLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(customLabel)
//**** constraint to UIImageView ****
//setup space with imageview and label
let horizontalCons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[myView]-10-[myLabel]-10-|", options: .alignAllCenterY, metrics: nil, views: ["myLabel":customLabel, "myView":customImageView])
self.addConstraints(horizontalCons)
//top to superview's margin is 10
let constraintTop = NSLayoutConstraint(item: customImageView, attribute: .topMargin, relatedBy: .equal, toItem: self, attribute: .topMargin, multiplier: 1.0, constant: 10)
//aspect ratio with 1:1
let constraintAspectRadio = customImageView.heightAnchor.constraint(equalTo: customImageView.widthAnchor, multiplier: 1.0)
//setup centerY with cell
let constraintY = NSLayoutConstraint(item: customImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraints([constraintTop, constraintAspectRadio, constraintY])
//**** constraint to UILabel ****
//setup centerY with cell
//let labelConstraintCenterY = NSLayoutConstraint(item: customLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
//setup uilabel's height is equal 21
//let labelConstraintHeight = NSLayoutConstraint(item: customLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 21)
//self.addConstraints([labelConstraintCenterY])
//Update use layout Anchor
customLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
customLabel.heightAnchor.constraint(equalToConstant: 21).isActive = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment