0

我在显示 5 个随机字符串中的 1 个的 uilabel 时遇到了一些问题。有时整个字符串显示没有问题,但通常情况下,某些文本会被截断。这是我目前拥有的:

// These are the 5 NSStrings which are placed in an array.
NSString *badOne = @"Bad? Your bill is nothing. I would consider that good service. SMDH.";
NSString *badTwo = @"You left out the amount dude.";
NSString *badThree = @"I can't tell you what the tip should be, if you don't tell me how much you dropped.";
NSString *badFour = @"Forgetting something?";
NSString *badFive = @"The tip should be over 9000... /n kidding.";

NSArray *badComments = [[NSArray alloc] initWithObjects:badOne, badTwo, badThree, badFour, badFive, nil];

// A random string is selected and assigned to badJoke.    
int rand = arc4random()%5;

NSString *badJoke = [badComments objectAtIndex:rand];

// Here's the problematic code:    
[_mainLabel setText:(badJoke)];
[_mainLabel setFrame:CGRectMake(50, 295, 200, 80)];
_mainLabel.adjustsFontSizeToFitWidth = NO;
_mainLabel.numberOfLines = 0;

[_amountTextField resignFirstResponder];

// This is a separate label, completely unrelated.    
[_tipAmount setText:@""];

因此,例如,有时它可能会显示“不好?您的帐单是否”。我也试过没有 setFrame 线,但没有运气。

任何帮助,将不胜感激。谢谢。

4

1 回答 1

0

理想的解决方案是计算在标签内显示文本所需的确切框架......

NSString *badJoke = [badComments objectAtIndex:rand];

CGSize maximumSize = CGSizeMake(200, CGFLOAT_MAX);//you can give any max width which you feel that suits you...

UIFont *font = [UIFont systemFontOfSize:16];/Give your font size

CGSize size = [badJoke sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
//size.height will get you the total height of the lable to be created.

_mainLable=[[UILable alloc]initWithFrame:CGRectMake(50, 295, size.width, size.height)];
//if you haven't initialized.Or else you can use the same as you were using..[_mainLabel setFrame:CGRectMake(50, 295, size.width, size.height)];

_mainLabel.text= badJoke;

_mainLabel.lineBreakMode=NSLineBreakByWordWrapping;

_mainLabel.numberOfLines = 0;

我不确定语法,因为我在记事本上写了代码。希望它对你有用。快乐编码:)

于 2013-01-20T08:35:18.360 回答