標籤:
在cell.m檔案中
1)初始化方法中:
self.lalName=[[UILabel alloc] initWithFrame:CGRectMake(71, 5, 250, 40)]; [self addSubview:self.lalName];
2)建立方法:
//給使用者介紹賦值並且實現自動換行-(void)setIntroductionText:(NSString*)text{ //獲得當前cell的高度 CGRect frame=[self frame]; //文本賦值 self.lalName.text=text; CGSize size=CGSizeMake(300, 1000); //設定label的最大行數 self.lalName.numberOfLines=10; CGSize labelSize=[self.lalName.text sizeWithFont:self.lalName.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping]; self.lalName.frame=CGRectMake(self.lalName.frame.origin.x, self.lalName.frame.origin.y, labelSize.width, labelSize.height) ; //計算出自適應的高度 frame.size.height=labelSize.height+20; self.frame =frame; }
在ViewController中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *[email protected]"acell"; TextKitTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:acell]; if (!cell) { cell=[[[NSBundle mainBundle] loadNibNamed:@"TextKitTableViewCell" owner:self options:nil]lastObject]; } [cell setIntroductionText:@"where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you?where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you?"]; return cell; }
當然別忘記了返回給cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell=[self tableView:self.tableViewTextKit cellForRowAtIndexPath:indexPath]; NSLog(@"height===%f",cell.frame.size.height); return cell.frame.size.height;}
iOS UITableViewCell自適應高度