简体   繁体   中英

How can I implement a tab bar like the ones in Xcode?

There does not seem to be any standard AppKit control for creating a tab bar similar to the ones found in Xcode.

Any idea on whether this is possible or would I need to use a custom control of some sort, and if so any suggestions on whether any are available. 在此处输入图片说明

OK I figured it out by subclassing NSSegementedControl to get the desired behaviours.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM