您的位置:首页 > 产品设计 > UI/UE

iOS 7.1版本UILabel自动换行

2014-10-08 22:44 295 查看
<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代码



CGSize size = CGSizeMake(screenSize.width - self.horizontalMargin * 4.f, 1000.f);

if(IOS7_OR_LATER){

CGRect textRect = [text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:font} context:nil];

self.contentWidth = self.contentWidth!=0.f?self.contentWidth:textRect.size.width;

self.contentHeight = self.contentHeight!=0.f?self.contentHeight:textRect.size.height;

}else{

CGSize textSize = [text sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];

self.contentWidth = self.contentWidth!=0.f?self.contentWidth:textSize.width;

self.contentHeight = self.contentHeight!=0.f?self.contentHeight:textSize.height;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: