I have a warning that I can not delete
All paths through this function will call itself
My code:
extension UIView {
var isLowAlpha: Bool {
get {
return self.isLowAlpha
}
set {
self.isUserInteractionEnabled = !newValue
self.alpha = newValue ? 0.3 : 1
}
}
}
I can not modify the code with this, because I have an error extension must not contain stored property ..:
extension UIView {
var isLowAlpha: Bool {
didSet {
self.isUserInteractionEnabled = !isLowAlpha
self.alpha = isLowAlpha ? 0.3 : 1
}
}
}
What is the solution?
One possible solution is to revert the process:
var isLowAlpha: Bool {
get {
return !isUserInteractionEnabled
}
set {
isUserInteractionEnabled = !newValue
alpha = newValue ? 0.3 : 1
}
}
or better, since you are not interested in the getter, make it a function:
func setIsLowAlpha(_ lowAlpha: Bool) {
self.isUserInteractionEnabled = !lowAlpha
self.lowAlpha = newValue ? 0.3 : 1
}
Anyway, looking at your code, you probably want to implement that a view is disabled. That's usually a task for UIControl subclasses, not UIView.
Also note the same can be implemented using a wrapper view:
class AlphaView: UIView {
var isLowAlpha: Bool = false {
didSet {
isUserInteractionEnabled = !isLowAlpha
alpha = isLowAlpha ? 0.3 : 1
}
}
}
And put your views inside.
In the first case you were recursively calling the variable's getter so it would never return. The way to fix this would be with a stored property _isLowAlpha, but unfortunately, as the second error mentions, Swift extensions cannot contain stored variables; they can only contain computed properties. If you really needed to add another property you would need to instead subclass UIView instead of making an extension.
However, in this case you can kind of cheat as long as you are not setting the UIView's alpha property elsewhere by directly using the alpha property:
extension UIView {
var isLowAlpha: Bool {
get {
return self.alpha == 0.3;
}
set {
self.alpha = newValue ? 0.3: 1
self.isUserInteractionEnabled = !newValue
}
}
}
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