我想在UILabel中显示我的长文本。但是,我的设计具有UILabel的小尺寸框架。所以,我想截断我的长文本[见下文]:
例如:
UILabel Text:“我想在UILabel中显示我的长文本”
最近的结果:[使用lineBreakMode:]
预期结果:“我想......”
[注意:我希望在符合标签框架的单词之后进行截断。]
我希望你能感觉到我的预期结果。抱歉我的英文!。
答案 0 :(得分:1)
我不确定是否有API。如果你没有得到答案。您可以使用以下逻辑来实现这不是最佳逻辑。
-(NSString *) textThatFits:(NSString *) originalText font:(UIFont *) font
{
NSArray *array = [originalText componentsSeparatedByString:@" "];
NSString *stringThatFits;
for (int i = 0 ; i < [array count]; i++)
{
NSString *tempString = [stringThatFits stringByAppendingFormat:@" %@", array[i]];
CGRect boundingRect = [tempString boundingRectWithSize:CGSizeMake(999, 999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil];
if (boundingRect.size.width < self.yourLabel.width) {
return stringThatFits;
}
else
{
stringThatFits = tempString;
}
}
return stringThatFits;
}
答案 1 :(得分:0)
根据OP例外结果和@Naveen逻辑,我开发了有效但有一定限制的代码。
限制:
设计
控件:UIButton,UITextField,UILabel
代码:
-(IBAction)actionDisplayTextWithTruncate:(id)sender{
lblFinalResult.frame=CGRectMake(60, 345, 55, 21);
NSString *strGivenText, *strFuncResult, *stringThatFits;
int spaceCount;
//Custom Truncate Function
strGivenText=txtFldGivenText.text;
arrForGivenText_Words = [strGivenText componentsSeparatedByString:@" "];
stringThatFits=@"";
strFuncResult=@"";
for (int i = 0 ; i < [arrForGivenText_Words count]; i++)
{
/* must follow @" %@" - a space before %@ */
NSString *tempString = [stringThatFits stringByAppendingFormat:@" %@", arrForGivenText_Words[i]];
CGRect boundingRect = [tempString boundingRectWithSize:CGSizeMake(999, 999) options:NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:lblFinalResult.font} context:nil];
if (boundingRect.size.width > lblFinalResult.frame.size.width) //Breakpoint1
{
if(i==0){
[lblFinalResult setText:@"..."];
return;
}
else{
for (int j = 0 ; j < i; j++)
{
strFuncResult = [strFuncResult stringByAppendingFormat:@"%@ ",arrForGivenText_Words[j]];
NSLog(@"Present_a1: %@", strFuncResult);
}
strFuncResult = [strFuncResult substringToIndex:strFuncResult.length-(strFuncResult.length>0)];
lblFinalResult.frame= CGRectMake(lblFinalResult.frame.origin.x, lblFinalResult.frame.origin.y, lblFinalResult.frame.size.width+10, lblFinalResult.frame.size.height);
strFuncResult=[strFuncResult stringByAppendingString:@"..."];
[lblFinalResult setText:strFuncResult];
return;
}
}
else{
stringThatFits = tempString;
NSLog(@"Present_a2: %@", stringThatFits);
}
}
[lblFinalResult setText:stringThatFits];
}