gpt4 book ai didi

ios - 如何设置自定义 UIView 属性

转载 作者:行者123 更新时间:2023-11-28 11:34:54 27 4
gpt4 key购买 nike

我正在尝试创建星级控制子类。我的评分控制类中有一个名为 rating 的可选变量,我希望在创建 View 后能够对其进行更改,但由于某种原因它始终为 nil。

如何在 StarRatingView 类中设置可以更改的属性,如下例所示?

class StarRatingView: UIStackView {

var rating: Int?

override init(frame: CGRect) {
super.init(frame: frame)
print(rating) // <<<---- Prints "nil" -----
addStarsBasedOnRating()
}

required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}


// How I'd like to access rating <<<<-------
func addStarsBasedOnRating() {
if rating == someNumber {
// do something
}
}

}

这就是在初始化它的类中创建评级控件的方式。

let ratingView: StarRatingView = {
let view = StarRatingView()
view.rating = 4
return view
}()

最佳答案

您正在尝试在设置之前打印该值。试试这个:

class StarRatingView: UIStackView {

var rating: Int? {
didSet {
addStarsBasedOnRating()
}
}

func addStarsBasedOnRating() {
// make sure rating is not nil
guard let rating = rating else {
// maybe you want to reset the view in here
return
}

if rating == someNumber {
// do something
}
}

}

关于ios - 如何设置自定义 UIView 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733615/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com