Swift/UIView/drawrect - 如何在需要时更新 drawrect

标签 swift uiview drawrect updating

我是 Swift 的新手,正在尝试让一个非常简单的应用程序运行。我想要做的就是让 UIView.drawRect 在我按下按钮时更新。它会在应用程序首次加载时更新/绘制,然后无论我尝试什么,它都不会更新。几天来我一直在努力解决这个问题,但我找不到任何帮助。

我创建了:

  • 单 View 应用

  • 一个按钮,作为一个 Action 链接到 View Controller

  • 一个新类,Test_View,继承 UIView

View Controller 代码:

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

}

测试_查看代码:

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 指定一个指定的初始化程序(init with frame)。然后使您的对象 f 成为类常量或变量(取决于您的需要),以便可以在项目范围内访问它。此外,您必须将其添加为 View 的 subview 。它看起来像这样:

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

    }

}

关于Swift/UIView/drawrect - 如何在需要时更新 drawrect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678582/

相关文章:

ios - CoreImageContext 的 CreateCGImage 产生了错误的 CGRect

ios - UITableViewCell var "table view cell"从未发生过变化

ios - UIView 背景大小问题

ios - 动画边界更改时具有 CALayer 有线效果的自定义 View

swift - 自定义 UIView 中的无效上下文 0x0

ios - 通过循环 drawRect 为自定义贝塞尔曲线路径设置动画

ios - 四舍五入 UIImage 并添加边框

ios - AVAudioEngine 分离 channel

swift - 如何在 ViewController 中调用 View ?

ios - 绘制以画笔形状结尾的线条?