如何固定UIButton的sizeToFit / sizeThatFit中的宽度?

时间:2019-04-28 04:11:41

标签: ios uibutton sizetofit

我发现sizeToFit或sizeThatFits将改变UIButton的当前宽度。

UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 200, 40);
btn.backgroundColor = [UIColor redColor];
[btn.titleLabel setText:@"ssdkfjsakdfjsakfjaksdjfkasjfkasjkfasjkfsajfkasjkas"];
btn.titleLabel.numberOfLines = 0;
[btn setTitle:@"ssdkfjsakdfjsakfjaksdjfkasjfkasjkfasjkfsajfkasjkas" forState:UIControlStateNormal];
[self.view addSubview:btn];

NSLog(@"before sizeToFit: %@",NSStringFromCGRect(btn.frame));
CGSize size = [btn sizeThatFits:CGSizeMake(200, 1000)];
[btn sizeToFit];

NSLog(@"after sizeToFit:%@",NSStringFromCGRect(btn.frame));
NSLog(@" sizeThatFits:%@",NSStringFromCGSize(size));

,输出将是:

before sizeToFit: {{100, 100}, {200, 40}}
after sizeToFit:{{100, 100}, {392, 34}}
sizeThatFits:{392, 34}

这不是我想要的行为,如果我希望sizeToFit根据其原点宽度将按钮框架调整为适当的高度。如何做到这一点?

1 个答案:

答案 0 :(得分:1)

如果要更改由sizeToFit设置的大小,则需要重写sizeThatFits方法。创建UIButton的子类,如下所示:

迅速:

class MyButton: UIButton {
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let sizeThatFits = super.sizeThatFits(size)
        return CGSize(width: sizeThatFits.width, height: self.frame.height)
    }
}

目标C:

@implementation MyButton

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize sizeThatFits = [super sizeThatFits:size];
    return CGSizeMake(sizeThatFits.width, self.frame.size.height);
}

@end

并使用子类化按钮而不是UIButton。

UIButton* btn = [MyButton buttonWithType:UIButtonTypeCustom];

参考:Apple Doc: sizeToFit