Skip to content

Instantly share code, notes, and snippets.

@froggomad
Last active February 13, 2021 22:36
Show Gist options
  • Save froggomad/8be72cf53865fa40d0a5cb629482ba79 to your computer and use it in GitHub Desktop.
Save froggomad/8be72cf53865fa40d0a5cb629482ba79 to your computer and use it in GitHub Desktop.
BorderView protocol
// blueprint
/// This protocol is constrained to types that conform to UIView - which is most UI elements
protocol BorderView: UIView {
func addBorder(borderWidth: CGFloat, borderColor: CGColor)
}
// default implementation (optional)
extension BorderView {
func addBorder(borderWidth: CGFloat = 1, borderColor: CGColor = UIColor.lightGray.cgColor) {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor
}
}
// adopt
class MyBorderedView: UIView, BorderView {
func commonInit() {
addBorder()
}
// override is required for existing methods we want to use
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// this is a required initializer for all UIViews - used by the storyboard. in programmatic applications, it's often common to see this produce a FatalError as a signal to other developers not to use that initializer
// since we're using storyboards... it's pretty important lol
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
}
class MyBorderedTextField: UITextField, BorderView {
func commonInit() {
addBorder()
}
// override is required for existing methods we want to use
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// this is a required initializer for all UIViews - used by the storyboard. in programmatic applications, it's often common to see this produce a FatalError as a signal to other developers not to use that initializer
// since we're using storyboards... it's pretty important lol
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
}
// instantiate
let view: BorderView = MyBorderedTextField()
print(view.layer.borderWidth)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment