使用自动布局约束设置NSButton文本插图

8
我正在使用OSX(而不是iOS),Xcode 8.2和Objective-C。我有两个带约束条件的按钮。这两个按钮都有居中的标题,并且通过约束条件具有相同的宽度。当涉及到另一种语言时,按钮会变得更宽以适应更长的文本。但我想在按钮边框和文本之间留出一些空间。IB中的标题插图选项对于NSButtons不存在,我没有找到任何等效的解决方案。任何帮助都将不胜感激。

enter image description here

底部按钮的限制条件:(“新项目”是顶部按钮)

enter image description here

3个回答

11

就像在UILabel中所做的那样,您需要覆盖intrinsicContentSize只读属性

以下是覆盖NSButton的示例,其中包含可以通过属性检查器在xib/storyboard文件中设置值的属性

//CustomButton.h file

@interface CustomButton : NSButton

@property (nonatomic, assign) IBInspectable CGFloat horizontalPadding;
@property (nonatomic, assign) IBInspectable CGFloat verticalPadding;

@end

//CustomButton.m file

@implementation CustomButton

- (NSSize) intrinsicContentSize{
    CGSize size = [super intrinsicContentSize];
    size.width += self.horizontalPadding;
    size.height += self.verticalPadding;
    return size;
}

@end

快乐编码 ‍


但是 NSButtonBezelView 的大小仍然不正确。 - Iulian Onofrei

10

这是我在Swift 4中使用的方法。

class Button: NSButton {

    @IBInspectable var horizontalPadding   : CGFloat = 0
    @IBInspectable var verticalPadding    : CGFloat = 0

    override var intrinsicContentSize: NSSize {
        var size = super.intrinsicContentSize
        size.width += self.horizontalPadding
        size.height += self.verticalPadding
        return size;
    }
}

1

Swift 5

我是这样让它对我发挥作用的:

在Storyboard中将这个类设置为您的按钮单元格。

class CustomNSButtonCell: NSButtonCell {

@IBInspectable var imagePaddingLeft   : CGFloat = 0
@IBInspectable var imagePaddingTop    : CGFloat = 0
@IBInspectable var textPaddingLeft   : CGFloat = 0
@IBInspectable var textPaddingTop    : CGFloat = 0

override func drawImage(_ image: NSImage, withFrame frame: NSRect, in controlView: NSView) {

    let newFrame = NSRect.init(
        origin: .init(x: frame.minX + imagePaddingLeft, y: frame.minY + imagePaddingTop),
        size: frame.size)

    super.drawImage(image, withFrame: newFrame, in: controlView)
}

override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
     let newFrame = NSRect.init(
               origin: .init(x: frame.minX + textPaddingLeft, y: frame.minY + textPaddingTop),
               size: frame.size)
    super.drawTitle(title, withFrame: newFrame, in: controlView)
    return newFrame
}

}

你可以通过Storyboard设置图像的左右和上下内边距以及文本的左右和上下内边距。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接