我在uilabel上遇到一点麻烦,应该显示5个随机字符串中的1个。有时整个字符串显示没有问题,但更多时候,一些文本被切断。这是我现在拥有的:
// 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线,没有运气。
任何帮助将不胜感激。感谢。
答案 0 :(得分: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;
我不确定语法,因为我在记事本上写了代码。希望它对你有用。快乐编码:)