2017-09-23 29 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

如果我風格定製,那麼我不能設置任何東西!沒關係。我將創建一個自定義原型單元格並使用它。 –

相關問題