Swift 使用@IBInspectable时何时使用didset或get set
在看了不同的教程之后。我不知道何时使用didset或get set来更新变量。 有没有人能更详细地解释一下何时使用didset或get setSwift 使用@IBInspectable时何时使用didset或get set,swift,Swift,在看了不同的教程之后。我不知道何时使用didset或get set来更新变量。 有没有人能更详细地解释一下何时使用didset或get set @IBInspectable var circleColor: UIColor = UIColor.redColor() { didSet { //after properties are set in storyboard, update here circleLayer.strokeColor = circleColor.C
@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
}
}
对于圆半径,它不必使用didset来更新其值。我搞不懂。这里我给你举一个例子,试着解释一下如何使用,希望对你有所帮助。
我将这个类用于UIView,用于did set和get set,故事板我的类名是“MyCustomView”
您可以将其与story board一起使用,并将该类与“UIView”一起导入
之后你会看到一些
你们可以直接在这里设置观察短号的半径,阴影和阴影
您可以直接在故事板内部看到结果,而无需运行代码
在此输出此代码
非常清楚地解释了set
与didSet
在用法上的差异
总之
willSet
应在设置值之前用于执行某些操作。(此时不更新该值)
set
用于更新值
didSet
如果要在设置值后执行任何操作(此时值已更新)
同时
如果实现set
,还需要实现get
但是didSet
也可以使用,而无需实施任何其他方法@IBInspectable将与两种属性类型一起使用:
- 将didSet{}用于存储的属性
didSet是一个属性观察者
在以下示例中:firstName和lastName是存储的属性 fullName是一个计算属性:
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)
还可以查看语言指南:(属性)
关于属性和@IBInspectable的最后一点说明:可以使用计算属性与存储属性(支持属性)的组合来实现值的验证:以下是一个示例:
//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
}
}
//在0和5之间绑定
var界限:Int=3{
迪塞特{
渲染()
}
}
@我看得见
风险值评级:整数{
设置{
如果newValue=0{
boundRating=newValue
渲染()
}
}
得到{
返回边界
}
}
在我的示例代码中,不必使用didset或getset来更新圆半径。但我也可以通过在故事板中设置来改变它。所以我无法获取它请检查您在UIView中导入的内容,如您的IBDesignable的@IBDesignable公共类ClassName?否则你可以用我的密码。我想你弄错了。我想说我可以在属性检查器中更改圆半径,即使我没有使用didset或getset来更新代码中的值
//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
}
}