所以在我的 Swift OS X 应用程序中,我有一个自定义 View 和一个按钮。当我启动我的应用程序时,我的 View 显示一个红色椭圆形,我需要将该绘图更改为 drawRectangle()
- 当我单击我的按钮时的方法。
我的自定义 View 类 MyView
如下所示:
import Cocoa
import AppKit
class MyView: NSView {
var isTrue = true
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
if isTrue {
DrawingMethods.drawOval()
} else {
DrawingMethods.drawRectangle()
}
}
@IBAction func buttonPressed(sender: AnyObject) {
isTrue = false
// Now I need to update the view, so it draws rectangle isntead of oval. How I do that?
}
}
我有我的 DrawingMethods
类:
import Cocoa
public class DrawingMethods: NSObject {
public class func drawOval() {
let color = NSColor(calibratedRed: 1, green: 0, blue: 0, alpha: 1)
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(64, 54, 50, 45))
color.setFill()
ovalPath.fill()
}
public class func drawRectangle() {
let color = NSColor(calibratedRed: 1, green: 0, blue: 0, alpha: 1)
let rectanglePath = NSBezierPath(rect: NSMakeRect(136, 12, 34, 34))
color.setFill()
rectanglePath.fill()
}
}
那么我怎样才能让我的自定义 View 绘制矩形而不是椭圆形呢?
最佳答案
在设置isTrue = false
后在 View 上调用setNeedsDisplayInRect()
。这将通知 View 它需要重绘并且将再次调用 drawRect
。
您的 buttonPressed
函数应该在包含自定义 View 的 ViewController
中定义
import Cocoa
class ViewController: NSViewController {
@IBOutlet customView: MyView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonPressed(sender: AnyObject) {
customView.isTrue = false
customView.setNeedsDisplayInRect(customView.bounds)
}
}
或者,您可以将 View 的 needsDisplay
属性设置为 true
以重绘整个 View :
customView.needsDisplay = true
关于macos - 在 Swift OS X 应用程序中单击按钮时更改自定义 View 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994840/