首先,您需要为UIView指定一个指定的初始化程序(以frame初始化)。然后将您的对象
f设为类的常量或变量(取决于您的需要),以便可以在项目范围内对其进行访问。另外,您必须将其添加为视图的子视图。看起来像这样:
import UIKitclass ViewController: UIViewController { let f = Test_View(frame: CGRectMake(0, 0, 50, 50)) override func viewDidLoad() { super.viewDidLoad() view.addSubview(f) } @IBAction func buttonPressed(sender: UIButton) { f.setNeedsDisplay() }}class Test_View: UIView { override init(frame: CGRect) { super.init(frame: frame) } required init?(prer aDeprer: NSCoder) { super.init(prer: aDeprer) } override func draw(_ rect: CGRect) { let h = rect.height let w = rect.width let color:UIColor = UIColor.yellow let drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5)) let bpath:UIBezierPath = UIBezierPath(rect: drect) color.set() bpath.stroke() NSLog("drawRect has updated the view") }}


