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

问题描述 投票:0回答:3

我使用的是 OSX(不是 iOS)、Xcode 8.2、Objective-C

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

任何帮助表示赞赏

底部按钮的约束:(“新建项目”是顶部按钮)

objective-c autolayout interface-builder xcode8 nsbutton
3个回答
11
投票

您必须像在 UILabel 中一样覆盖内在ContentSize 只读属性

这是一个使用属性覆盖 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

快乐编码👨u200d💻


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
投票

斯威夫特5

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

将此类设置为故事板中按钮的单元格。

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

您可以设置图像的左侧和顶部填充。 文本的左侧和顶部填充通过故事板。

© www.soinside.com 2019 - 2024. All rights reserved.