简体   繁体   中英

When to use didset or get set when using @IBInspectable

After looking at different tutorial. i don't know when to use didset or get set to update the variable. Could anyone explain a little bit more detail for when to use didset or get set?

 @IBInspectable var circleColor: UIColor = UIColor.redColor() {
    didSet { //after properties are set in storyboard, update here
        circleLayer.strokeColor = circleColor.CGColor
        self.toggleButon()
    }
}
/**
    Radius of RadioButton circle.
*/
@IBInspectable var circleRadius: CGFloat = 5.0
@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
}

for circle radius, it doesn't have to use didset to update its value. i can't get it.

Here i am giving you one example and try to explain you how to use, hope it will helpful for you.

I am using this class for UIView here for did set and get set with Story Board my class name here "MyCustomView"

import Foundation
import UIKit
import QuartzCore

/// Computed properties, based on the backing CALayer property, that are visible in Interface Builder.
@IBDesignable public class MyCustomView: UIView {
    /// When positive, the background of the layer will be drawn with rounded corners. Also effects the mask generated by the `masksToBounds' property. Defaults to zero. Animatable.
    @IBInspectable var cornerRadius: Double {
        get {
            return Double(self.layer.cornerRadius)
        }
        set {
            self.layer.cornerRadius = CGFloat(newValue)
        }
    }

    /// The width of the layer's border, inset from the layer bounds. The border is composited above the layer's content and sublayers and includes the effects of the `cornerRadius' property. Defaults to zero. Animatable.
    @IBInspectable var borderWidth: Double {
        get {
            return Double(self.layer.borderWidth)
        }
        set {
            self.layer.borderWidth = CGFloat(newValue)
        }
    }

    /// The color of the layer's border. Defaults to opaque black. Colors created from tiled patterns are supported. Animatable.
    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(CGColor: self.layer.borderColor!)
        }
        set {
            self.layer.borderColor = newValue?.CGColor
        }
    }

    /// The color of the shadow. Defaults to opaque black. Colors created from patterns are currently NOT supported. Animatable.
    @IBInspectable var shadowColor: UIColor? {
        get {
            return UIColor(CGColor: self.layer.shadowColor!)
        }
        set {
            self.layer.shadowColor = newValue?.CGColor
        }
    }

    /// The opacity of the shadow. Defaults to 0. Specifying a value outside the [0,1] range will give undefined results. Animatable.
    @IBInspectable var shadowOpacity: Float {
        get {
            return self.layer.shadowOpacity
        }
        set {
            self.layer.shadowOpacity = newValue
        }
    }

    /// The shadow offset. Defaults to (0, -3). Animatable.
    @IBInspectable var shadowOffset: CGSize {
        get {
            return self.layer.shadowOffset
        }
        set {
            self.layer.shadowOffset = newValue
        }
    }

    /// The blur radius used to create the shadow. Defaults to 3. Animatable.
    @IBInspectable var shadowRadius: Double {
        get {
            return Double(self.layer.shadowRadius)
        }
        set {
            self.layer.shadowRadius = CGFloat(newValue)
        }
    }
}

And you can use this with story board import this class with your "UIView"

在此输入图像描述

after you will see some and you directly set here view cornet radius, shadow and Shadow

在此输入图像描述

and result you can see inside your storyboard directly without running code

Output here from this code

在此输入图像描述

This answer explains the difference in usage of set vs didSet quite clearly.

IN SUMMARY

willSet should be used for doing something before the value is set. (the value is not updated at this point).

set is to update the value

didSet if you want to do anything after the value is set (the value has been updated at this point)

ALSO

if you implement set , you will also need to implement get

but didSet can also be used without having to implement any other method

@IBInspectable will work with both property kinds:

  • Use didSet{} for stored properties :
    didSet is a property observer.

  • Use set{} get{} for computed properties .


in the following example: firstName And lastName are stored properties.

fullName is a Computed property:

struct Person{
    var firstName:String
    var lastName:String{
        didSet{
            //property observer
            print("It was set")
        }
    }

    var fullName:String{
        get{
            return "\(firstName)-\(lastName)"
        }
        set{
            let split = newValue.split(separator: "-")

            firstName = String(split.first ?? "")
            lastName = String(split.last ?? "")
        }
    }
}

var p = Person(firstName: "Moshe", lastName: "Doe")

print(p.firstName)
print(p.lastName)
print(p.fullName)

p.fullName = "Jhon-Doe"

print(p.firstName)
print(p.lastName)
print(p.fullName)

Also look into the language guide: (Properties)

https://docs.swift.org/swift-book/LanguageGuide/Properties.html

One final note about properties and @IBInspectable :
Validation of a value may be achieved using a combo of a computed property with a stored property (Backing property): Here is an example:

//Bound between 0 and 5
var boundRating:Int = 3{
    didSet{
        renderRating()
    }
}

@IBInspectable
var rating:Int{
    set{
        if newValue <= 5 && newValue >= 0{
            boundRating = newValue
            renderRating()
        }
    }
    get{
        return boundRating
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM