今天在修改代码的时候发现了一些问题,便做了一下优化
先上图说事:
在这里的播放列表cell中是两个UILabel分别显示的是作品名和作者名。没修改之前,两个lab实在XIB中初始化和设置约束的,出来的效果就是无法动态的根据字符串长度来增加lab的宽度,或是做了一下设置后,虽然可以实现效果,但是在出现边界情况时就无法控制了(比如:作品名就超出了cell的宽度。。。。。)
搜索了一会后发现有的解决方案是说:将cell的autolayout勾选掉(去掉);—没有尝试 自我感觉会对不通屏幕尺寸产生不知道的效果 ,还是乖乖拿代码写吧。
上代码:
//
// MusicListTableViewCell.m
//
#import "MusicListTableViewCell.h"
@implementation MusicListTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
self.labName = [[UILabel alloc] init];
self.labName.backgroundColor = [UIColor clearColor];
self.labName.font = FONT(QB_FONT_SIZE + 2);
self.labName.textAlignment = NSTextAlignmentLeft;
self.labName.textColor = UIColorHex(0x323232);
self.labName.numberOfLines = 1;
self.labName.lineBreakMode = NSLineBreakByTruncatingTail;
[self addSubview:self.labName];
self.labAuthor = [[UILabel alloc] init];
self.labAuthor.backgroundColor = [UIColor clearColor];
self.labAuthor.font = FONT(QB_FONT_SIZE - 2);
self.labAuthor.textAlignment = NSTextAlignmentLeft;
self.labAuthor.textColor = UIColorHex(0x898989);
self.labAuthor.numberOfLines = 1;
self.labAuthor.lineBreakMode = NSLineBreakByTruncatingTail;
[self addSubview:self.labAuthor];
}
-(void)cellShowMusic:(MusicModel*)model{
NSString *praiseNumber = model.name;
CGSize textSize = [praiseNumber boundingRectWithSize:CGSizeMake(MAXFLOAT, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FONT(QB_FONT_SIZE + 2)} context:nil].size;
CGFloat width = ceil(textSize.width);
if (width > self.bounds.size.width - 70) {
width = self.bounds.size.width - 70;
}
self.labName.frame = CGRectMake(10, 0, width, self.bounds.size.height);
[self.labAuthor setFrame:CGRectMake(width + 20, 2, self.bounds.size.width - width - 50, self.bounds.size.height - 2)];
self.labName.text = model.name;
self.labAuthor.text = [NSString stringWithFormat:@"- %@",model.singer];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
主要的思路就是在显示数据的时候计算字符串的长度,从而去动态的设置lab的宽度:
CGSize textSize = [praiseNumber boundingRectWithSize:CGSizeMake(MAXFLOAT, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FONT(QB_FONT_SIZE + 2)} context:nil].size;
之后做的一些操作就是在出现一个lab字数过长时主动的限制宽度。