macos - 在 Swift OS X 应用程序中单击按钮时更改自定义 View 绘图

标签 macos swift drawing nsview

所以在我的 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/

相关文章:

ios - 更改图像色调颜色内存泄漏

javascript - 从勇者斗恶龙中绘制史莱姆

c# - 自定义控件中的双缓冲子控件(C#)

macos - 无法制作 pkg-config

macos - 在哪里可以获得用于 Mac OS Classic 开发的资源?

python - 如何使 python 程序从命令行普遍可执行?

swift - 在 SwiftUI 中显示小吃吧消息

arrays - 将枚举数组转换为其代表字符串数组

java - 在 Canvas 上绘图,平滑缩放并绘制更多内容

python - 如何在 mac os x 上使用带有 python3.8 而不是 python3.9 的 Gunicorn?