简体   繁体   中英

How to add Constraints programmatically to default imageView and textLabel of UITableViewCell

I am currently creating my cell like this

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
  cell.imageView.image = [UIImage imageNamed:image];
  cell.imageView.tintColor = [UIColor whiteColor];
  cell.textLabel.text = @"Push me";
  cell.textLabel.textColor = [UIColor whiteColor];
  cell.userInteractionEnabled = YES;
  return cell;

Everything is working fine but some of my text which is long gets truncated at the end. How can i avoid that?? I don't want to set the numberOfLines property.

Is there a way i can arrange my imageView and textlabel a bit via constraints so that my text looks fine. I tried adding constraints to contentView of cell but that make my cell all weird.

I am new to iOS development and learning. Any help will be greatly appreciated.

If you don't want to set numberOfLines . adjustsFontSizeToFitWidth property will set your content bound to width without truncating it. but it will decrease font size if required.

cell.textLabel.adjustsFontSizeToFitWidth = true

There is no need to add constraint programmatically, Step 1 - Drag and drop the cell on UITableview Step 2 - Design your cell with image view and label , use constraints Step 3 - Create CustomCell.h and CustomCell.m file which will be inherited from UITableViewCell Step 4 - create IBOutlet for image view and label in CustomCell.h Step 5 - In your ViewController -

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
   cell.textLabel.text = [self.dataAraay objectAtIndex:indexPath.row];
return cell;
}

https://www.raywenderlich.com/129059/self-sizing-table-view-cells

UIImageView *imgarrow=[[UIImageView alloc]init ];

imgarrow.frame=CGRectMake(230,2, 27, 27);

imgarrow.image=[UIImage imageNamed:@"check_mark@2x.png"];

[cell addSubview:imgarrow];

//write same code for UILabel

//change rectmake values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM