Skip to content

Instantly share code, notes, and snippets.

@crisbit
Last active December 22, 2021 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisbit/a66e691adabdc400698f79384f326827 to your computer and use it in GitHub Desktop.
Save crisbit/a66e691adabdc400698f79384f326827 to your computer and use it in GitHub Desktop.
Custom view which can be rendered by Interface Builder and a running iOS app alike. It uses autolayout for the subviews.
//
// MYCustomView.swift
// StatWidget
import UIKit
/**
Custom view which can be rendered by Interface Builder
and a running iOS app alike. It uses autolayout for the
subviews.
*/
@IBDesignable class MYCustomView: UIView {
// MARK: View initialization and update
// Do not change the value of this property
// manually. If the constraints have already
// been created it will be set to false.
private var shouldCreateConstraints = true
// Used by running iOS app
required init?(coder: NSCoder) {
super.init(coder: coder)
createSubviews()
}
// Used by Inteface Builder
override init(frame: CGRect) {
super.init(frame: frame)
createSubviews()
}
// Updates the layout of the subviews whenever
// needed.
override func layoutSubviews() {
if(shouldCreateConstraints) {
createConstraints()
shouldCreateConstraints = false
}
// else { updateConstraints() }
}
// MARK: "Outlets" for subviews
private var label: UILabel!
// MARK: Properties inspectable by Interface Builder
// They get set immediately after init(CGRect) is called
// so make sure the views they are referring to have
// already been initialized. Else you will get a nil
// reference error.
@IBInspectable var bgColor: UIColor = UIColor.whiteColor() {
didSet {
self.backgroundColor = bgColor
}
}
@IBInspectable var textColor: UIColor = UIColor.blackColor() {
didSet {
label.textColor = textColor
}
}
// MARK: Subviews creation and setup
// Never call this method manually. It will be called by layoutSubviews
// whenever needed.
private func createSubviews() {
label = UILabel()
label.font = UIFont.boldSystemFontOfSize(15)
label.text = "Ehi, I'm centered!"
// Set to false if you are going to use constraints to position it,
// else it won't show up correctly
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
}
// MARK: Constraints creation and setup
// Never call this method manually. It will be called by layoutSubviews
// whenever needed.
private func createConstraints() {
label.centerXAnchor.constraintEqualToAnchor(self.centerXAnchor).active = true
label.centerYAnchor.constraintEqualToAnchor(self.centerYAnchor).active = true
}
// MARK: Rest of the class
// Add additional code here if needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment