【问题标题】:Can I set my autolayout constraints so that an imageview is set to the height of the image我可以设置我的自动布局约束,以便将图像视图设置为图像的高度
【发布时间】:2016-09-08 16:17:48
【问题描述】:

我正在构建一个动态表格视图单元格。高度根据加载的内容是动态的。我遇到了图像视图高度的挂断。当前加载的图像填充宽度为 100% 的图像视图。如果表格视图单元格没有图像,是否可以在我的图像视图上设置自动布局约束,以便隐藏图像视图(高度为 0)?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewTileCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tileCell"];

    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"TableViewTileCell" bundle:nil] forCellReuseIdentifier:@"tileCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"tileCell"];
    }
    cell.tileView.layer.borderColor = [UIColor blackColor].CGColor;
    cell.tileView.layer.borderWidth = 1.0f;

    [cell.contentView setBackgroundColor:[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0]];

    NSString *url=[self.resultsArray[indexPath.row] valueForKey:@"imageURL"];

    cell.tileTitle.text = [self.resultsArray[indexPath.row] valueForKey:@"title"];
    cell.tileDate.text = [self.resultsArray[indexPath.row] valueForKey:@"date"];
    cell.tileContent.text = [self.resultsArray[indexPath.row] valueForKey:@"summary"];

    if(![url isEqualToString:@""]){ //If we got a url value back load the image
        [cell.tileImageview setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    }

    return cell;
}

【问题讨论】:

  • 你能发布你的cellForRowAtIndexPath吗?

标签: ios uitableview uiimageview autolayout


【解决方案1】:

如果表格视图单元格没有图像,是否可以在我的图像视图上设置自动布局约束,以便隐藏图像视图(高度为 0)?

使整个单元格内容成为一个垂直的 UIStackView。在cellForRow 中,隐藏图像视图。堆栈视图具有以您描述的方式更改约束的奇妙能力:当图像视图隐藏时,约束将发生变化,图像视图将占用零空间,其他视图占用整个空间。

替代方案并不可怕:您只需要自己做 UIStackView 会做的事情 — 删除代码中的空图像视图并调整约束,在 cellForRow 中。将约束和视图一起交换进出界面是标准做法,而且很容易做到。

【讨论】:

  • 谢谢马特!我已经开始拼凑代码以有条件地更改约束的过程,但开始感觉使用自动布局应该更容易。
猜你喜欢
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2022-01-21
  • 1970-01-01
  • 2021-05-13
相关资源
最近更新 更多