Swift/UIView/drawrect - 如何在需要时获取drawrect进行更新

Tom*_*m M 12 updating uiview drawrect swift

我是学习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.")
    }

}
Run Code Online (Sandbox Code Playgroud)

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")            

    }

}
Run Code Online (Sandbox Code Playgroud)

(注意:每次按下按钮都会更新日志,所以这不是问题.只是显示器永远不会改变.而且,我尝试用随机坐标绘制矩形,所以不是它正在更新但是我'我没有看到它.)

谢谢你的帮助!

Ian*_*Ian 18

首先,您需要为UIView指定一个指定的初始化程序(init with frame).然后使对象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")

    }

}
Run Code Online (Sandbox Code Playgroud)