我在项目当中自定义了一个叫做Notice的视图类,作用是给用户提供一些提示信息。如果是短信息还好,一行就可以搞定了。如果提示的信息太长,一行显示不全的话,就只能多行显示了。
下面摘录代码:
UILabel *label = [[UILabel alloc]init];
[label setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.8]];
[label setTextColor:[UIColor whiteColor]];
[label setFont:[UIFont systemFontOfSize:POP_ALERT_MSG_SIZE]];
[label setText:msg];
label.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
label.textAlignment = NSTextAlignmentCenter;
label.clipsToBounds = YES;
label.layer.cornerRadius = 5;
label.alpha = 1;
label.numberOfLines = 0;//根据最大行数需求来设置
label.lineBreakMode = NSLineBreakByTruncatingTail;
CGSize maximumLabelSize = CGSizeMake([UIScreen mainScreen].bounds.size.width-20, MAXFLOAT);
//关键语句
CGSize expectSize = [label sizeThatFits:maximumLabelSize];
//别忘了把frame给回label,如果用xib加了约束的话可以只改一个约束的值
label.frame = CGRectMake(0, 0, expectSize.width+ 14, expectSize.height+ 14);
//label.frame = CGRectMake(0, 0, expectSize.width, expectSize.height);//这样是正好塞满,不太好看,可以在宽和高上加一个冗余
[self setFrame:CGRectMake(0, 0, label.frame.size.width, label.frame.size.height)];
[self setCenter:CGPointMake(CGRectGetMidX([UIScreen mainScreen].bounds), CGRectGetMidY([UIScreen mainScreen].bounds) - 40)];
[self addSubview:label];
self.alpha = 0;
网友评论