Here is an UIView
extension written in ObjectiveC to easily create view for using Auto-layout:
+(id)autolayoutView
{
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
it invokes [self new]
so any subclass of UIView can use this method. How can I achieve this in Swift?
Swift allows omitting self when you want to access instances properties. When a method parameter has the same name as an instance property, you have to explicitly use self. myVariable = myVariable to make a distinction.
In Swift, the self keyword refers to the object itself. It is used inside the class/structure to modify the properties of the object. You can assign initial values to properties in the init() method via self.
In Swift self is a special property of an instance that holds the instance itself. Most of the times self appears in an initializer or method of a class, structure or enumeration. The motto favor clarity over brevity is a valuable strategy to follow.
“self” as an Object in Swift This self is a reference to the current object (“instance”) of a class (or struct), within that class. You can work with self as if it's a variable or object within the class (or struct), that is the class (or struct). It's an essential concept of Object-Oriented Programming (OOP).
OK, this appears to be the solution. The type must have a required
initializer with the correct parameter list (in this case no parameters).
class SubView: UIView {
override required init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class func autolayoutView() -> UIView {
var view = self()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With