2017-09-16 26 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 
    } 
}