【问题标题】:Change Custom Views drawing when button is clicked in Swift OS X app在 Swift OS X 应用程序中单击按钮时更改自定义视图绘图
【发布时间】:2014-11-18 12:52:44
【问题描述】:

所以在我的 Swift OS X 应用程序中,我有一个自定义视图和一个按钮。当我启动我的应用程序时,我的视图显示一个红色椭圆,当我单击我的按钮时,我需要将该绘图更改为drawRectangle()-method。

我的自定义视图类 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()
    }
}

那么我怎样才能让我的自定义视图绘制矩形而不是椭圆?

【问题讨论】:

    标签: macos swift drawing nsview


    【解决方案1】:

    设置isTrue = false后在视图上调用setNeedsDisplayInRect()。这将通知视图它需要重绘,并且将再次调用drawRect

    您的buttonPressed 函数应在包含自定义视图的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)
        }
    }
    

    或者,您可以将视图的needsDisplay 属性设置为true 以重绘整个视图:

    customView.needsDisplay = true
    

    【讨论】:

    • 对不起,我非常不擅长编程,英语很差,我不知道标志在这种情况下是什么意思。我只知道“捕获'标志'”:) 那么我应该在我的'buttonPressed'函数中调用该函数吗?你能在代码中显示你是怎么做到的吗?
    • 这样吗? setNeedsDisplayInRect() 括号里应该写什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多