如何实现Xcode中的标签栏?

时间:2018-07-27 06:50:37

标签: macos toolbar tabbar

似乎没有任何标准的AppKit控件可用于创建类似于Xcode中的标签栏。

关于是否可行或是否需要使用某种自定义控件的任何想法,如果可以,请提供有关是否可用的任何建议。enter image description here

1 个答案:

答案 0 :(得分:0)

好吧,我通过将NSSegementedControl子类化以获得所需的行为来解决这个问题。

import Cocoa

class OSSegmentedCell: NSSegmentedCell {

    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        // Do not call super to prevent the border from being draw
        //super.draw(withFrame: cellFrame, in: controlView)

        // Call this to ensure the overridden drawSegment() method gets called for each segment
        super.drawInterior(withFrame: cellFrame, in: controlView)
    }
    override func drawSegment(_ segment: Int, inFrame frame: NSRect, with controlView: NSView) {
        // Resize the view to leave a small gap
        let d:CGFloat = 0.0
        let width = frame.height - 2.0*d
        let dx = (frame.width - width) / 2.0
        let newRect = NSRect(x: frame.minX+dx, y: frame.minY, width: width, height: width)

        if let image = self.image(forSegment: segment) {
            if self.selectedSegment == segment {
                let tintedImage = image.tintedImageWithColor(color: NSColor.blue)
                tintedImage.draw(in: newRect)
            } else {
                image.draw(in: newRect)
            }
        }
    }
}
extension NSImage {
    func tintedImageWithColor(color:NSColor) -> NSImage {
        let size        = self.size
        let imageBounds = NSMakeRect(0, 0, size.width, size.height)
        let copiedImage = self.copy() as! NSImage

        copiedImage.lockFocus()
        color.set()
        __NSRectFillUsingOperation(imageBounds, NSCompositingOperation.sourceIn)
        copiedImage.unlockFocus()

        return copiedImage
    }
}