更改UIButton状态时不更新内部大小

时间:2013-07-31 22:14:47

标签: iphone ios objective-c uikit interface-builder

我有一个包含UIButton的UIView。 UIButton为UIControlStateNormal(“Follow”)和UIControlStateSelected(“Following”)状态设置了2个标题。我在UIButton上使用自动布局,它有一个约束,距离超视图顶部一定距离,另一个距离超视图左侧有一定距离。我也使用了“尺寸适合内容”。

当我从代码中将按钮设置为处于选定状态时,标题会正确更改,但UIButton的固有宽度不会改变,因此当从“Follow”更改为“Follow”时,文本将被椭圆化。 / p>

self.selected = self.following;

enter image description here enter image description here

当我以不同的方式处理问题时,只需在有人点击按钮时更改UIControlStateNormal的文本,该按钮就会正确地改变大小。

NSString *title = (self.following) ? @"Following" : @"Follow"
[self setTitle:title forState:UIControlStateNormal];

enter image description here enter image description here

这是UIKit中的错误吗?我希望按钮可以更改其内在大小,以便在状态发生变化时正确反映文本的新大小,特别是因为除了2按钮状态的文本之外还有其他我想要更改的内容。

4 个答案:

答案 0 :(得分:23)

就像David Caunt在评论中指出的那样,调用invalidateIntrinsicContentSize会导致自动布局调整按钮大小以适应新内容。

self.selected = self.following;
[self invalidateIntrinsicContentSize];

PS。大卫,如果你想发布你的commant作为答案我会删除我的。

答案 1 :(得分:1)

在您的故事板中选择您的UIButton,然后在顶部选择编辑器>大小以适合内容大小。

编辑:试试这个:

[self.myButton setTitle:@"Following" forState:UIControlStateSelected];
[self.myButton sizeToFit];

答案 2 :(得分:1)

对我来说,设置 contentEdgeInsets 给了我唯一可靠的解决方案。

我使用自定义按钮和背景图片。因此,切片出现在图片中。事实证明,切片图像的方式也会影响内在的内容大小!测试一下!所以,我必须确保我在不同状态的图像之间切换相同。我也使用了属性字符串。这里发布的解决方案对我的案例不起作用。

我在一天(!)的实验后发现,在按钮上设置足够的contentEdgeInsets值会使其在使用autolayout更改标题时表现正常。如果您这样做,则无需使内在内容大小无效或调用任何布局代码。

您可以在代码或IB中设置contentEdgeInsets。

self.button.contentEdgeInsets = UIEdgeInsetsMake(10.0, 16.0, 10.0, 16.0);

我认为除了var属性外,Swift代码是相同的。

Apple在文档中说明了这一点:"该按钮使用此属性来确定intrinsicContentSize和sizeThatFits:。"。

enter image description here

答案 3 :(得分:0)

这是一个错误,还是只是它的方式,我不知道,但看起来你必须解决它 - 我不认为你做错了什么。如果您想在每次触摸后在所选内容之间切换,则可以执行以下操作:

- (IBAction)buttonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.button setTitle:@"Following" forState:UIControlStateNormal];
        //Do whatever else you want to do here for the selected state
    }else{
        [self.button setTitle:@"Follow" forState:UIControlStateNormal];
    }
}