我是学习Swift的新手,并且正在尝试运行一个非常简单的应用程序。我要做的就是 让UIView.drawRect在我按下按钮时更新 。无论我尝试什么,它都会在应用程序首次加载时更新/绘制,然后再更新/绘制。我已经为此奋斗了几天,但我找不到任何帮助。
我创建:
单视图应用程序
一个按钮,作为操作链接到视图控制器
一个新的类Test_View继承了UIView
ViewController代码:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var f = Test_View() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Button_Pressed(sender: AnyObject) { var f = Test_View() f.setNeedsDisplay() NSLog("Button pressed.") } }
Test_View代码:
class Test_View: UIView { override func drawRect(rect: CGRect) { let h = rect.height let w = rect.width var color:UIColor = UIColor.yellowColor() var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5)) var bpath:UIBezierPath = UIBezierPath(rect: drect) color.set() bpath.stroke() NSLog("drawRect has updated the view") } }
(注意:每次按下按钮,日志都会更新,这不是问题。只是显示永远不会改变。而且,我尝试绘制带有随机坐标的矩形,因此不是更新,而是我没看到。)
谢谢你的帮助!
首先,您需要为UIView指定一个指定的初始化程序(以frame初始化)。然后将您的对象f设为类的常量或变量(取决于您的需要),以便可以在项目范围内对其进行访问。另外,您必须将其添加为视图的子视图。看起来像这样:
f
import UIKit class 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?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } 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") } }