【问题标题】:How to add imageView width/height programmatically?如何以编程方式添加 imageView 宽度/高度?
【发布时间】:2018-12-16 06:46:49
【问题描述】:

如何更改UIImageViewwidth/height。我有很多不同 width/height 的图片,我希望它们以 imageView 的大小显示。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    let city = nicosiaPlaces [indexPath.row]
    cell?.textLabel?.text = city
    cell?.imageView?.image = UIImage(named: city)
    cell?.imageView?.frame.size = CGSize(width: 10, height: 10)
    return cell!
}

我想让这行代码工作:

cell?.imageView?.frame.size = CGSize(width: 10, height: 10)

【问题讨论】:

  • 如果我没记错的话,sizeframe 的属性是 ready only(只有 get,没有 set)。因此,取而代之的是,检索frame,并在保留原点的情况下重新计算它,并使用cell?.imageView?.frame = CGRect(origin: cell?.imageView?.frame.origin, size: CGSize(width: 10, height: 10))cell?.imageView?.frame = CGRect(x: cell?.imageView?.frame.origin.x, y: cell?.imageView?.frame.origin.y, width: 10, height: 10) 更改大小
  • 那没用 :(
  • 您希望实际的UIImageView 调整大小,还是希望固定大小并在其中调整实际图像的大小?
  • 这看起来只是您上一个问题stackoverflow.com/questions/51226153/…的副本

标签: swift uitableview uiimageview image-size


【解决方案1】:

替换:

cell?.imageView?.frame.size = CGSize(width: 10, height: 10)

与:

cell?.imageView?.translatesAutoresizingMaskIntoConstraints = false
cell?.imageView?.heightAnchor.constraint(equalToConstant: 10).isActive = true
cell?.imageView?.widthAnchor.constraint(equalToConstant: 10).isActive = true

您似乎希望 cell 是可选的,但如果上述方法不起作用,请尝试删除问号。

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 2014-08-22
    • 1970-01-01
    • 2011-04-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    相关资源
    最近更新 更多