2017-09-16 28 views
1

使用swift3,我想允許用戶創建圖片或簡單文本帖子的帖子。我有一切工作正常,除了當我創建一個文本後,單元格中的UIImageView填充了TableViewCell中的空間。理想情況下,如果用戶創建一個文本文章,TableViewCell將只包含標題標籤的所有內容,但不包括UIImageView(見圖)。我怎麼去解決這個問題。使用swift3動態調整TableViewCell的大小,使其不帶圖像

研究:https://www.youtube.com/watch?v=zAWO9rldyUEhttps://www.youtube.com/watch?v=TEMUOaamcDAhttps://www.raywenderlich.com/129059/self-sizing-table-view-cells

目前代碼

func configureCell(post: Post){ 
    self.post = post 
    likesRef = FriendSystem.system.CURRENT_USER_REF.child("likes").child(post.postID) 
    userRef = FriendSystem.system.USER_REF.child(post.userID).child("profile") 

    self.captionText.text = post.caption 
    self.likesLbl.text = "\(post.likes)" 

    self.endDate = Date(timeIntervalSince1970: TimeInterval(post.time)) 

    userRef.observeSingleEvent(of: .value, with: { (snapshot) in 
     let snap = snapshot.value as? Dictionary<String, Any> 
     self.currentUser = MainUser(uid: post.userID, userData: snap!) 
     self.userNameLbl.text = self.currentUser.username 
     if let profileImg = self.currentUser.profileImage { 
      self.profileImg.loadImageUsingCache(urlString: profileImg) 
     } else { 
      self.profileImg.image = #imageLiteral(resourceName: "requests_icon") 
     } 
    }) 

    // This is where I belive I need to determine wether or not the cell should have an image or not. 
     if let postImg = post.imageUrl { 
      self.postImg.loadImageUsingCache(urlString: postImg) 
     } 

enter image description here

回答

1

我看你用故事創造你的用戶界面,在這種情況下你可以爲您的添加高度限制(確保將它連接到您的單元格以便在代碼中使用它),並在需要時更改tableview的約束和高度。

class MyCell: UITableViewCell { 

    @IBOutlet var postImage: UIImageView! 
    @IBOutlet var postImageHeight: NSLayoutConstraint! 
} 


class ViewController: UITableViewController { 

    var dataSource: [Model] = [] 

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     //Cell without image 
     if dataSource[indexPath.row].image == nil { 
      return 200 
     } 
     //Cell with image 
     return 350 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell 

     //Adjust the height constraint of the imageview within your cell 
     if dataSource[indexPath.row].image == nil { 
      cell.postImageHeight.constant == 0 
     }else{ 
      cell.postImageHeight.constant == 150 
     } 
     return cell 
    } 
}