gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:26:01 28 4
gpt4 key购买 nike

我是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com