2017-09-23 69 views
0

我使用UIImageView,titleLabel和描述标签附带的默认UITableViewCell。我想为我的UIImageView有一个固定的大小,所以所有的图像都是相同的大小。目前,它看起来像这样:UIImageView内置UITableViewCell iOS中的固定大小11

enter image description here

的单元格的行高度为“自动”,在这里是UITableView中的性能。

enter image description here

我怎样才能让我的UIImageView固定大小?

的图像被异步下载,如下图所示:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
     let dish = self.dishes[indexPath.row] 
     cell.textLabel?.text = dish.title 
     cell.imageView?.image = UIImage(named: "placeholder") 

     cell.detailTextLabel?.text = dish.description 

     cell.imageView?.setImageFor(url: URL(string: dish.imageURL)!) { image in 
      cell.imageView?.image = image 
      cell.imageView?.translatesAutoresizingMaskIntoConstraints = false 
      cell.imageView?.widthAnchor.constraint(equalToConstant: 50) 
      cell.imageView?.heightAnchor.constraint(equalToConstant: 50) 
      cell.setNeedsLayout() 
     } 

     return cell 

    } 

的UIImageView + Additions.swift

func setImageFor(url :URL, completion: @escaping (UIImage) ->()) { 

     DispatchQueue.global().async { 

      let data = try? Data(contentsOf: url) 

      if let data = data { 

       let image = UIImage(data: data) 

       DispatchQueue.main.async { 

        completion(image!) 

       } 
      } 
     } 
    } 

enter image description here

+0

尝试设置'imageView.contentMode = .scaleAspectFit'。 – krlb

+0

我做到了,它什么都没做! –

回答

0

您正试图改变的height anchorwidth anchorUIImageView在你的里面。你不应该这样做,如果你需要,请确保你正在更新main thread中的布局。

UIImageViewtop, bottom, leading, and trailing anchor可能等于superView,你的情况,这是tableViewCell,并考虑到您的UITableViewCell■找汽车的高度。这些导致您的UIImageView尺寸不等。

由于您使用的界面生成器,尝试布置你UIImageView像这样:

enter image description here

正如你所看到的,我有我的固定的宽度和我UIImageView的高度。

最后,不要忘记设置您的UIImageViewcontentMode并勾选clipToBounds为yes。

+0

谢谢! imageView.image在主线程中设置。我粘贴了setImageURL的代码。出于某种原因,我不能在UIImageView上设置任何约束,如图所示。一次,我再次使用默认的UITableViewCell,而不是创建原型单元格。也许这是Xcode 9中的一个bug。 –

+0

你可以:)。点击你的TableViewCell并将它的'style'设置为Custom。尝试一下。 – Glenn

+0

如果我风格定制,那么我不能设置任何东西!没关系。我将创建一个自定义原型单元格并使用它。 –