自定义视图未显示

时间:2019-09-21 16:53:56

标签: ios swift

我想创建自定义视图,但未加载。

我正在尝试Parallelogram view using UIBezierPath

class ViewController: UIViewController {
    @IBOutlet weak var testView: UIView!

    override func viewWillAppear(_ animated: Bool) {
        let customeView = CustomeView()
        customeView.draw(CGRect(x: 0, y: 0, width: 50, height: 50))
        testView.addSubview(customeView)
    }
}

class CustomeView: UIView {
    override func draw(_ rect: CGRect) {
        let path = UIBezierPath()

        path.move(to: CGPoint(x: bounds.minX , y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))

        path.close()
        UIColor.red.setFill()
        path.fill()
    }
}

我希望创建自定义视图。

1 个答案:

答案 0 :(得分:4)

永远不要自己调用视图的draw方法。删除该行。适当的解决方案是为视图提供适当的框架。并且您应该在viewDidLoad中设置视图。

override func viewDidLoad() {
    super.viewDidLoad()

    let customeView = CustomeView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    testView.addSubview(customeView)
}