Skip to content

Instantly share code, notes, and snippets.

@CharlesAE
Created October 15, 2018 01:45
Show Gist options
  • Save CharlesAE/dc40f4667b3fd1b27daeef083db229a2 to your computer and use it in GitHub Desktop.
Save CharlesAE/dc40f4667b3fd1b27daeef083db229a2 to your computer and use it in GitHub Desktop.
import UIKit
class UserCell: UICollectionViewCell {
//Creating the ImageView, assigning it an image from the assets folder
let userImage: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.image = #imageLiteral(resourceName: "user")
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
//Creating the label
let userName: UILabel = {
let label = UILabel()
label.text = "Name"
label.textColor = .black
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
layoutCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layoutCell() {
//Background is transparent
backgroundColor = .clear
//Add subviews to the cell
addSubview(userImage)
addSubview(userName)
//Constraints with visual format
//Label will fill the view from right to left with 1px of space on each side
addConstraintsWithFormat("H:|-1-[v0]-1-|", views: userName)
//Image is given a max width of 52px, and will span the view from right to left
addConstraintsWithFormat("H:|[v0(52@1000)]|", views: userImage)
//Image is give na max height of 52 pixel, and will be placed above the label, label will have 2px of space underneath it
addConstraintsWithFormat("V:|[v0(52@1000)]-2@1000-[v1]|", views: userImage, userName)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment