实现效果图如下:
实现方法:
方法一:可以放两个label,设置布局
方法二:用UITextView实现
准备两个方法:方法1:根据字符串计算大小
- (CGFloat)getTextWidth:(NSString *)str{
CGSize maxSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
CGRect rect = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0]} context:nil];
return rect.size.width;
}
方法2: 根据传递的字符串格式化
具体代码 如下:
- (NSString *)getStr:(NSString *)str1 nextStr:(NSString *)str2 viewsW:(CGFloat)w {
// str1:头 str2:后面所跟内容 w :控件的宽度
self.textView.font = [UIFont systemFontOfSize:15.0];
CGFloat width = 0;
NSString *tempStr = str1;
NSString *resultStr = @"";
NSString *emptyStr = @"";
CGFloat maxWidth1 = w-30;
CGFloat width1 = [self getTextWidth:str1];
CGFloat maxWidth2 = maxWidth1 - width1;
while (width < width1) {
emptyStr = [NSString stringWithFormat:@"%@ ",emptyStr];
width = [self getTextWidth:emptyStr];
}
CGFloat resultW = 0;
BOOL isFirstLine = YES;
while (str2.length > 0) {
NSString *ss = [str2 substringToIndex:1];
tempStr = [NSString stringWithFormat:@"%@%@",tempStr,ss];
str2 = [str2 substringFromIndex:1];
if (isFirstLine) {
resultW = [self getTextWidth:tempStr];
if (resultW >= maxWidth1) {
isFirstLine = NO;
resultStr = [NSString stringWithFormat:@"%@%@\n",resultStr,tempStr];
if (str2.length > 0) {
resultStr = [NSString stringWithFormat:@"%@%@",resultStr,emptyStr];
}else {
break;
}
tempStr = @"";
}else {
if (str2.length <= 0) {
resultStr = [NSString stringWithFormat:@"%@%@\n",resultStr,tempStr];
break;
}
}
}else {
resultW = [self getTextWidth:tempStr];
if (resultW >= maxWidth2) {
resultStr = [NSString stringWithFormat:@"%@%@\n",resultStr,tempStr];
if (str2.length > 0) {
resultStr = [NSString stringWithFormat:@"%@%@",resultStr,emptyStr];
}else {
break;
}
tempStr = @"";
}else {
if (str2.length <= 0) {
resultStr = [NSString stringWithFormat:@"%@%@\n",resultStr,tempStr];
break;
}
}
}
}
return resultStr;
}
使用:
NSString *str1 = @"阿飞正传:";
NSString *str2 = @"我听别人说这世界上有一种鸟是没有脚的,它只能一直飞呀飞呀,飞累了就在风里面睡觉,这种鸟一辈子只能下地一次,那一次就是它死亡的时候.";
self.textView.font = [UIFont systemFontOfSize:15.0];
NSString *str11 = @"大话西游:";
NSString *str22 = @"曾经有一份真挚的感情摆在我的面前我没有珍惜,等我失去的时候才追悔莫及,人间最痛苦的事莫过于此,你的剑在我的咽喉上刺下去吧,不用在犹豫了!如果上天能给我一次再来一次的机会,我会对哪个女孩说三个字:我爱你,如果非要在这份爱上加一个期限,我希望是一万年!";
NSString *s = [NSString stringWithFormat:@"%@%@",[self getStr:str1 nextStr:str2 viewsW:[UIScreen mainScreen].bounds.size.width-24],[self getStr:str11 nextStr:str22 viewsW:[UIScreen mainScreen].bounds.size.width-24]];
self.textView.text = s;
注意点:调用格式化方法的时候传递的控件宽度要用屏幕的宽度-当前控件在屏幕上的左右间距
**字体的大小,都可以自己设置**