objective-cautolayoutinterface-builderxcode8nsbutton

NSButton text insets with autolayout constraints


I am on OSX (not iOS), Xcode 8.2, Objective-C

I have two buttons with constraints. Both buttons got centered titles and both have the same width (via constraints). No when it comes to another language the buttons grows wider to fit the longer text. But i'd like to have some space between the border of the button and the text. The title insets options in IB do not exist for NSButtons and i did not find any equivalent solutions.

Any help appreciated

enter image description here

Constraints for the bottom button: ("New project" is the top button)

enter image description here


Solution

  • You have to override intrinsicContentSize readonly property just like you would do in UILabel

    Here is an example of overriding NSButton with properties that you can set their values in your xib/storyboard file via attributes inspector

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

    Happy coding 👨‍💻