【问题标题】:How to add Constraints programmatically to default imageView and textLabel of UITableViewCell如何以编程方式将约束添加到 UITableViewCell 的默认 imageView 和 textLabel
【发布时间】:2023-04-08 04:28:01
【问题描述】:

我目前正在像这样创建我的单元格

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;

一切正常,但我的一些长文本在最后被截断。我怎样才能避免呢?我不想设置 numberOfLines 属性。

有没有办法我可以通过约束来安排我的 imageView 和 textlabel,这样我的文本看起来很好。我尝试向单元格的 contentView 添加约束,但这让我的单元格很奇怪。

我是 iOS 开发和学习的新手。任何帮助将不胜感激。

【问题讨论】:

标签: ios objective-c uitableview autolayout


【解决方案1】:

如果您不想设置numberOfLinesadjustsFontSizeToFitWidth 属性将设置您的内容绑定到宽度而不截断它。但如果需要,它会减小字体大小。

cell.textLabel.adjustsFontSizeToFitWidth = true

【讨论】:

  • 它对我来说很好用。谢谢!!但是有没有办法我可以在它的 imageView 和 textLabel 之间以编程方式向它添加约束。
  • 是的,您可以添加约束。请检查如何在 stackoverflow 中以编程方式添加约束。你会有很多结果要经历。如果不满意,请在评论中告诉我。我会通过更新我的答案在这里给你一个代码。
  • 我试过了。但是我现在的单元格看起来很奇怪...我将imageView和textLabel的AutoResizingMask转换为NO,然后将视觉约束添加到cell.contentView,例如字符串为H:|-[imageView]-[textLabel]-|但它不起作用......我也尝试在两者之间添加常量但仍然没有运气......
【解决方案2】:

无需以编程方式添加约束, 第 1 步 - 在 UITableview 上拖放单元格 第 2 步 - 使用图像视图和标签设计您的单元格,使用约束 第 3 步 - 创建将从 UITableViewCell 继承的 CustomCell.h 和 CustomCell.m 文件 第 4 步 - 在 CustomCell.h 中为图像视图和标签创建 IBOutlet 第 5 步 - 在您的 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

【讨论】:

    【解决方案3】:

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

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

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

    [单元格 addSubview:imgarrow];

    //为UILabel编写相同的代码

    //改变rectmake值

    【讨论】:

    • 我使用的是cell提供的默认imageView
    • 比自动调整掩码
    猜你喜欢
    • 1970-01-01
    • 2020-04-20
    • 2015-11-30
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多