具有自动布局约束的 NSButton 文本插入

NSButton text insets with autolayout constraints

我在 OSX(不是 iOS),Xcode 8.2,Objective-C

我有两个带约束的按钮。两个按钮的标题都居中并且宽度相同(通过约束)。不,当涉及到另一种语言时,按钮会变宽以适应较长的文本。但我希望在按钮的边框和文本之间有一些 space。 IB 中的标题插入选项对于 NSButtons 不存在,我没有找到任何等效的解决方案。

感谢任何帮助

底部按钮的约束:("New project" 是顶部按钮)

您必须像在 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

编码愉快‍

这就是 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;
    }
}

Swift 5

我以这种方式让它为我工作:

将此 class 设置为情节提要中按钮的单元格。

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
}

}

您可以设置图片的左内边距和上内边距。 以及故事板中文本的左内边距和上内边距。