1. 程式人生 > >IOS XIB中設定了約束後無法在程式碼中改變檢視的frame

IOS XIB中設定了約束後無法在程式碼中改變檢視的frame

今天在修改程式碼的時候發現了一些問題,便做了一下優化

先上圖說事:
這裡寫圖片描述

在這裡的播放列表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字數過長時主動的限制寬度。