1、封装一个nsobject 对象
@interface RkyMyControl : NSObject
+(UIButton*)createButtonWithimageName:(NSString*)imageName bgImageName:(NSString*)bgImageName title:(NSString*)title color:(UIColor *)color;
+(UILabel*)createLabelWithFont:(float)font Text:(NSString*)text Color:(UIColor *)color;
+(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font andwidth:(CGFloat)width;
@end
2、实现这些方法
#import "RkyMyControl.h"
@implementation RkyMyControl
+(UIButton*)createButtonWithimageName:(NSString*)imageName bgImageName:(NSString*)bgImageName title:(NSString*)title color:(UIColor *)color {
UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
if (imageName) {
[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}
if (bgImageName) {
[button setBackgroundImage:[UIImage imageNamed:bgImageName] forState:UIControlStateNormal];
}
if (title) {
[button setTitle:title forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateDisabled];
[button setTitleColor:color forState:UIControlStateNormal];
}
return button;
}
/*
options:NSStringDrawingTruncatesLastVisibleLine| NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading//采用换行模式
*/
+(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font andwidth:(CGFloat)width
{
CGRect rect = [string boundingRectWithSize:CGSizeMake(width, 800)//限制最大的宽度和高度
options: NSStringDrawingUsesLineFragmentOrigin//采用换行模式
attributes:@{NSFontAttributeName: font}//传入的字体字典
context:nil];
return rect.size;
}
+(UILabel*)createLabelWithFont:(float)font Text:(NSString*)text Color:(UIColor *)color
{
//[[UILabel appearance]setTextColor:[UIColor redColor]];
UILabel*label=[[UILabel alloc]init];
//设置字体大小
label.font=[UIFont systemFontOfSize:font];
label.textColor=color;
//设置对齐方式
label.textAlignment=NSTextAlignmentLeft;
//设置行数
label.numberOfLines=0;
//设置折行方式 NSLineBreakByCharWrapping NSLineBreakByWordWrapping
label.lineBreakMode=NSLineBreakByWordWrapping;
//设置阴影的颜色
// label.shadowColor=[UIColor yellowColor];
//设置阴影的偏移
// label.shadowOffset=CGSizeMake(2, 2);
//设置文字
if (text) {
label.text=text;
}
return label;
}
3、使用方法说明
//计算_activityTitle.height的高度 重新排列控件的frame
-(void)layoutSubView:(NSString *)titleStr
{
CGFloat titleHeight=[RkyMyControl sizeWithString:titleStr font:titleFont andwidth:titleWidth].height;
_activityTitle.height=titleHeight;
_activitytime.top=CGRectGetMaxY(_activityTitle.frame)+10;
_activityaddress.top=CGRectGetMaxY(_activitytime.frame)+5;
_activitymember.top=CGRectGetMaxY(_activityaddress.frame)+5;
lineL.top=CGRectGetMaxY(_activitymember.frame)+10;
}
在uitableView :-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
返回cell 的高度
IWActive *activeM=_commactivityArrary[indexPath.row];
CGFloat titleHeight=[RkyMyControl sizeWithString:activeM.title font:[UIFont systemFontOfSize:14] andwidth:150].height;
CGFloat cellHeight=titleHeight+75;
return cellHeight;
UItableViewCell文字自适应的高度就大功告成了!是不是很简单啊!