就像在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
我是这样让它对我发挥作用的:
在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设置图像的左右和上下内边距以及文本的左右和上下内边距。
NSButtonBezelView
的大小仍然不正确。 - Iulian Onofrei