Last active
November 20, 2021 05:16
-
-
Save kostapappas/a73863d5024a365626726d79b3649c68 to your computer and use it in GitHub Desktop.
Swift 4, custom UIView with explanations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyCustomView: UIView { | |
private var didSetupConstraints = false | |
//In Swift initializers are not inherited for subclasses by default | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
} | |
// Deserialize your object here | |
// required = subclasses of that class have to implement it too | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
} | |
// There are 3 phases to displaying a view: | |
// update constraints | |
// update layout | |
// layoutSubviews | |
// update display | |
// draw Rect | |
//its called when | |
//Its own bounds (not frame) changed | |
//The bounds of one of its direct subviews changed | |
//A subview is added to the view or removed from the view | |
//set the frame rectangles of your subviews directly | |
//setNeedsLayout(): If you want to force a layout update, call the setNeedsLayout() method instead to do so prior to the next drawing update. | |
//layoutIfNeeded(): If you want to update the layout of your views immediately, call the layoutIfNeeded() method | |
//use both setNeedsLayouts - layoutIfNeeded for instant use | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
//myProperty.frame = CGRect... | |
// intrinsic content size changes | |
// super.layoutSubviews() The second call to super.layoutSubviews() is optional but may be required | |
//if the intrinsic conent size of the view changes | |
} | |
//update AutoLayoutConstrains here | |
//runs more than once | |
//CAREFUL don't add new constrains - update the existent one | |
override func updateConstraints() { | |
if didSetupConstraints == false { | |
configureAutolayoutConstrains() | |
} | |
super.updateConstraints() | |
} | |
//put here your initial autoLayout Setup | |
private func configureAutolayoutConstrains () { | |
} | |
//Each UIView subclass should implement the intrinsicContentSize | |
//and return the size that it thinks its ok for it. | |
//If we didn’t know how wide the view is we | |
//would use UIViewNoIntrinsicMetric instead of the width | |
final override var intrinsicContentSize: CGSize { | |
return CGSize(width: UIView.noIntrinsicMetric, height: 20) | |
} | |
//is called immediately before a class instance is deallocated. | |
//cleanup yourself your own resources | |
//close filemanagers, remove observers etc | |
deinit { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment