我在自动布局环境中有一个NSButton子类。子类实现了mouseEntered:和mouseExited:方法,它们应该改变按钮图像的位置。在mouseEntered:它被更改为NSImageLeft(显示标题)和mouseExited:它被更改为NSImageOnly(不显示标题)。
Autolayout负责在我的视图层次结构中调整NSButton子类的大小,但它看起来并不平滑,因为根据是否要显示标题,它不使用CoreAnimation来调整按钮宽度。如何通过动画调整大小?
答案 0 :(得分:0)
打开动画组,启用隐式动画,更改按钮图像位置,然后强制布局:
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){
context.allowsImplicitAnimation = YES;
button.imagePosition = NSImageOnly;
[button.window layoutIfNeeded];
} completionHandler:nil];
答案 1 :(得分:0)
我使用以下方法解决了这个问题:
- (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
和widthConstraint
是我在awakeFromNib
期间定义的NSButton子类的属性。