iOS 7.1版本UILabel自动换行

<span style="font-size:24px;">  针对:iOS 7.1版本UILabel自动换行
</span>
<span style="font-size:24px;">实现代码:</span>
<pre name="code" class="objc"><span style="font-size:18px;">   NSString *strLable = @"rectA为UILabel的高度范围,300是预设的一个宽度,view预设的要加载到的UIView";
    CGRect rectA = [strLable boundingRectWithSize:CGSizeZero options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24]}context:nil];
    UILabel *labelB = [[UILabel alloc] init];
    labelB.text = strLable;
    labelB.numberOfLines = 0;
    labelB.lineBreakMode = NSLineBreakByCharWrapping;
    
    labelB.frame = CGRectMake(10, 300, 300, rectA.size.height * (rectA.size.width / 300));//两行*2  要是三行呢:使用NSLog:中((int)rectA.size.width / 300) -> 300是宽度可以替换
    
    [viewA addSubview:labelB];
    NSLog(@"rectA height = %f \n width = %f", rectA.size.height, rectA.size.width);
    NSLog(@"rectA.size.width / 300 = %d", ((int)rectA.size.width / 300));
 </span>

 

相关技术点:

 labelB.lineBreakMode = NSLineBreakByCharWrapping;

typedef NS_ENUM(NSInteger, NSLineBreakMode) {		/* What to do with long lines */
    NSLineBreakByWordWrapping = 0,     	/* Wrap at word boundaries, default */
    NSLineBreakByCharWrapping,		/* Wrap at character boundaries */
    NSLineBreakByClipping,		/* Simply clip */
    NSLineBreakByTruncatingHead,	/* Truncate at head of line: "...wxyz" */
    NSLineBreakByTruncatingTail,	/* Truncate at tail of line: "abcd..." */
    NSLineBreakByTruncatingMiddle	/* Truncate middle of line:  "ab...yz" */
} NS_ENUM_AVAILABLE_IOS(6_0);
上面是Xcode  5 中方法枚举
 

在ios7中使用的举例

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

例如:

OC代码   收藏代码
  1. CGSize size = CGSizeMake(screenSize.width - self.horizontalMargin * 4.f, 1000.f);  
  2.        if(IOS7_OR_LATER){  
  3.            CGRect textRect = [text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:font} context:nil];  
  4.            self.contentWidth = self.contentWidth!=0.f?self.contentWidth:textRect.size.width;  
  5.            self.contentHeight = self.contentHeight!=0.f?self.contentHeight:textRect.size.height;  
  6.        }else{  
  7.            CGSize  textSize = [text sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];  
  8.            self.contentWidth = self.contentWidth!=0.f?self.contentWidth:textSize.width;  
  9.            self.contentHeight = self.contentHeight!=0.f?self.contentHeight:textSize.height;  
  10.        }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值