Search code examples
objective-ccocoacore-animationautolayoutnsbutton

Animate NSButton resizing when modifying imagePosition property


I have an NSButton subclass in an autolayout environment. The subclass implements mouseEntered: and mouseExited: methods, which should change the positioning of the button's image. On mouseEntered: it is changed to NSImageLeft (showing the title) and on mouseExited: it is changed to NSImageOnly (not showing the title).

Autolayout takes care of the resizing of the NSButton subclass in my view hierarchy, but it does not look smooth as it is not using CoreAnimation for resizing the button width according to whether the title is to be shown or not. How can I let the resizing happen with an animation?


Solution

  • I solved it by using the following methods:

    - (void)mouseEntered:(NSEvent *)theEvent {
        NSSize titleStringSize = [self.title sizeWithAttributes:@{NSFontAttributeName:[NSFont     boldSystemFontOfSize:11.0]}];
        self.widthConstraint.animator.constant = titleStringSize.width+self.originalWidth+5.0;
    }
    
    - (void)mouseExited:(NSEvent *)theEvent {
        self.widthConstraint.animator.constant = self.originalWidth;
    }
    

    originalWidth and widthConstraint are properties of my NSButton subclass that are defined during awakeFromNib.