iOS长度不同可自动换行的标签
2016-04-14 本文已影响1770人
旅橙
- 写到一个类似新闻多图详情的页面,下方需要根据服务器返回的值绘制不定数量的标签.字符长度也不尽相同.需要进行动态计算长度和位置.
绘制可以实现自动换行的label/button
-
tagView就是放置buttons的view
#pragma mark - 尝试绘制自动换行的类型标签label/button- (void)createTypeBtnsView{ tagView = [[UIView alloc]initWithFrame:CGRectMake(10, 45 + 300*self.model.imagesArray.count, [DMDevceManager screenWidth]-20, 10)]; CGFloat positionX = 0.0; CGFloat positionY = 0.0; CGFloat bgViewWidth = [DMDevceManager screenWidth]-20; UIFont *btnTitleFont = [UIFont systemFontOfSize:13]; //如果有图片作为边框,使用注释 // UIImage *selImage = [UIImage imageNamed:@"greenCir1"]; // UIImage *norImage = [UIImage imageNamed:@"grayCir2"]; // CGFloat left = selImage.size.width/4; // CGFloat top = selImage.size.height/4; for(int i = 0;i<self.model.typesArray.count;i++) { //下面的方法 CGFloat btnWidth = [DMUtils textWidth:self.model.typesArray[i] Font:btnTitleFont height:25]; if(positionX + btnWidth > bgViewWidth){ positionX = 0; positionY += 30; } UIButton *btn = [DMUITool createButtonWithFrame:CGRectMake(positionX, positionY, btnWidth, 25) title:self.model.typesArray[i] target:self action:@selector(typeBtnClick:) tag:i+30000]; btn.titleLabel.font = btnTitleFont; btn.backgroundColor = Color(103, 206, 249); btn.layer.masksToBounds = YES; btn.userInteractionEnabled = YES; btn.layer.cornerRadius = 12; [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; positionX += (btnWidth+5); //如果有图片作为边框,从4分之1处拉伸,承接上一个注释 // [btn setBackgroundImage:[selImage stretchableImageWithLeftCapWidth:left topCapHeight:top] forState:UIControlStateSelected]; // [btn setBackgroundImage:[norImage stretchableImageWithLeftCapWidth:left topCapHeight:top] forState:UIControlStateNormal]; [tagView addSubview:btn]; }
下面的方法是来计算每个label上文字所占宽度
/*
*获取文字所占宽度
*@param text 文本内容,计算式包括了换行空格等
*@param font 字体
*@param height:指定高度下计算,若不设限使用CGFLOAT_MAX
*/
+ (CGFloat)textWidth:(NSString *)text Font:(UIFont *)font height:(CGFloat)height
{
if(![DMDevceManager isiOS7])
{
return [text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, height) lineBreakMode:NSLineBreakByCharWrapping].width;
}
else{
if(text.length <= 0)
{
return 0;
}
UITextView *textView = APPDELEGATE.textView;
textView.text = text;
textView.font = font;
CGSize size = [textView sizeThatFits:CGSizeMake(CGFLOAT_MAX, height)];
return size.width;
}
}
效果如图:
可自动换行的buttons