Home > Enterprise >  UIButton width or line break mode problem
UIButton width or line break mode problem

Time:09-28

I'm programmatically adding UIButton objects to an UIScrollView. The result I'm getting is that the height of the button is calculated properly, i.e. there is a space for a second line, but the text does not wrap, it rather continues to flow as if the button has infinite width. I used to have UITextView objects instead of the buttons, and that worked flawlessly. I just cannot set the buttons to layout the same way the text views did.

Here's a code snipplet:

UIButton* sButton = [[UIButton alloc] initWithFrame:CGRectMake(0, yPos, sWidth - 5, height)];
sText = [[NSMutableString alloc] initWithString:@"quite a long string that does not fit in one line, no chance"];
sButton.titleLabel.font = font;
sButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[sButton setLineBreakMode:NSLineBreakByWordWrapping];
[sButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
[sButton setTitle:sText forState:UIControlStateNormal];
[sButton sizeToFit];

And this is the result I'm getting: enter image description here

How can I make the button text wrap?

CodePudding user response:

This is the only solution I've found that works: https://stackoverflow.com/a/4978003/963022

I ended up creating a custom button implementation and overriding:

- (CGSize)sizeThatFits:(CGSize)size {

    int diff = 0;
    // for the width, subtract DIFF for the border
    // for the height, use a large value that will be reduced when the size is returned from sizeWithFont
    CGSize tempSize = CGSizeMake(size.width - diff, 1000);

    CGSize stringSize = [self.titleLabel.text
                     sizeWithFont:self.titleLabel.font
                     constrainedToSize:tempSize
                     lineBreakMode:UILineBreakModeWordWrap];
    return CGSizeMake(size.width - diff, stringSize.height);
}
  • Related