Swift:将子视图添加到另一个子视图

时间:2017-09-26 18:00:46

标签: swift view

我在为视图添加子视图方面苦苦挣扎。 progress变量在其viewcontroller的viewDidLoad()中设置。 progressView框架大小设置正确,它只是添加似乎出错的子视图。对于什么是缺失的任何想法?

class ProgressBar: UIView {
    var progressView = UIView()
    var progress: CGFloat? {
        didSet {
            setProgressBar(progress: progress!)
        }
    }

    func setProgressBar(progress: CGFloat) {
        self.layer.masksToBounds = true
        let progressViewWidth: CGFloat = self.frame.width * progress
        progressView.backgroundColor = .red
        progressView.frame = CGRect(origin: frame.origin,
                                    size: CGSize(width: progressViewWidth, height: frame.height))
        self.addSubview(progressView)
    }
}

1 个答案:

答案 0 :(得分:2)

progressView.frame = CGRect(origin: frame.origin, size: CGSize(width: progressViewWidth, height: frame.height))

它应该像

一样被替换
progressView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: progressViewWidth, height: frame.height))

progressView的位置与progressBar' s

有关