如何设置自定义 UIView 属性

How to Set Custom UIView Properties

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

如何在 StarRatingView class 中拥有可以更改的属性,如下例所示?

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    
        }
    }

}

这就是在 class 中创建评级控件并对其进行初始化的方式。

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
        }
    }

}