-
-
Save ksmandersen/dd849faa99fffeded2e46cd393e0c65d to your computer and use it in GitHub Desktop.
class AwesomeView: GenericView { | |
let bestTitleLabel = UILabel().then { | |
$0.textAlignment = .Center | |
$0.textColor = .purpleColor()tww | |
} | |
let otherTitleLabel = UILabel().then { | |
$0.textAlignment = . | |
$0.textColor = .greenColor() | |
} | |
override func configureView() { | |
super.configureView() | |
addSubview(bestTitleLabel) | |
addSubview(otherTitleLabel) | |
// Configure constraints | |
} | |
} |
You can also do something very similar in Swift already without "Then":
let bestTitleLabel: UILabel = {
$0.textAlignment = .Center
$0.textColor = .purpleColor()
return $0
}(UILabel())
You can put whatever constructor you'd like inside there as well.
@mrgrauel I know that is the Objective-C and storyboard style to keep references to views weak, and with good reasons to avoid retain-cycles. But I actually do prefer to keep the references strong. I have had places where views are not added at initialization or I want to remove and add them again. And as long as you're not doing anything weird with how you add the views into the view hierarchy you don't get retain cycles. Make the views weak only makes them more annoying to deal with when referencing them later.
@ryanwilson: I wasn't aware of this technique. It's quite clever. I do still prefer the then syntax, but it's nice to know that it can be achieved without 3rd party code
Do you like it that the properties are retained by its superview and the AwesomeView instance? I prefer to use weak variables with a private setter for UIKit instances which are added to a view-hierarchy. If the view is removed from its superview the label is still available in your solution, but shouldn't it only be available as long as it's in the view-hierachy?
This is how I prefer to do it. What do you think?