我正在尝试创建星级评分控件子类。我的评分控制类中有一个名为rating
的可选变量,我希望在创建视图后可以对其进行更改,但是由于某些原因,该变量始终为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
}()
答案 0 :(得分:2)
您正在尝试在设置值之前打印该值。试试这个:
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
}
}
}