是否可以制作圆形NSButton?

时间:2016-03-03 19:25:11

标签: swift macos nsbutton

我正在尝试创建自定义形状NSButton。特别是我试图使用自定义图像制作一个圆形按钮。我在创建自定义UIButton时找到了a tutorial,并尝试将其改编为NSButton。但是有一个很大的问题。 clipsToBounds似乎只是iOS(

这是我的代码:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var mainButton: NSButton!
    var size = 32

    override func viewDidLoad() {
        super.viewDidLoad()
        configureButton()
                // Do any additional setup after loading the view.
    }
    func configureButton()
    {
        mainButton.wantsLayer = true
        mainButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay
        mainButton.layer?.cornerRadius = 0.5 * mainButton.bounds.size.width
        mainButton.layer?.borderColor = NSColor(red:0.0/255.0, green:122.0/255.0, blue:255.0/255.0, alpha:1).CGColor as CGColorRef
        mainButton.layer?.borderWidth = 2.0
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

我做错了什么?如何制作圆形NSButton?您能否就替换clipsToBounds提出任何建议?

因为这是我迄今为止所能得到的:

enter image description here

3 个答案:

答案 0 :(得分:5)

不要玩角半径。圆圈没有角落。要使按钮显示为圆圈,请将按钮的layer屏蔽为圆圈。

答案 1 :(得分:3)

您正在根据按钮的宽度设置半径。通过截屏的外观,当您开始时按钮不是正方形,因此圆角不能创建圆。

答案 2 :(得分:3)

NSButton是NSView的子类,因此NSView中的所有方法(例如drawRect(_ :))也可用于NSButton。

因此,请创建一个新的 Button.swift ,您可以在其中绘制自定义布局

import Cocoa

class Button: NSButton {

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        // Drawing code here.
        var path = NSBezierPath(ovalInRect: dirtyRect)
        NSColor.greenColor().setFill()
        path.fill()
    }

}

enter image description here

精彩教程Here。它是iOS,但非常相似!

相关问题