我想创建自定义视图,但未加载。
我正在尝试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()
}
}
我希望创建自定义视图。
答案 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)
}