【发布时间】:2019-10-20 14:22:43
【问题描述】:
我正在设置一个“新闻源”样式的表格视图,并希望我的自定义单元格根据两个因素自动调整大小:
1) 所代表的帖子是否包含图像 - 如果不包含图像,则单元格应该表现得好像没有适当的 ImageView 和大小
2) 如果帖子确实包含图像,则 ImageView 应根据图像高度设置其高度(因此,ImageView 没有高度限制)并且单元格应相应调整大小
在尝试完成此操作时,我的细胞出现了极其不稳定的行为。最初,带有图像的第一个单元格将正确填充。但是,当您滚动浏览时,图像的大小开始出现错误,而其他图像则根本不显示。
我的图片正在通过 Google Firebase 异步下载。
我在单元格中使用自动布局,并为所有子视图正确设置了顶部、底部、前导和尾随约束。该问题似乎仅限于 ImageView。其他元素不受影响。
我尝试在 ImageView 上设置高度约束,并根据是否要显示图像以编程方式调整它的大小。这似乎没有帮助。
这是我的 tableview 委托方法:
// Tableview methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mPosts!.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 600
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = newsfeed.dequeueReusableCell(withIdentifier: "newsfeedCell") as! NewsfeedCell
let post = mPosts![indexPath.row]
cell.posterNameDisplay.text = post.getPosterName() + " " + (mAccount?.getFamilyName())!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy @ hh:mm a"
let dateString = dateFormatter.string(from: post.getTimeStamp())
cell.timestampDisplay.text = dateString
cell.postMessageDisplay.text = post.getPostMessage()
AccountUtils.loadProfilePhoto(ProfileId: post.getPosterId(), ProfilePhoto: cell.profilePhoto)
cell.profilePhoto.layer.borderWidth = 1.0
cell.profilePhoto.layer.masksToBounds = false
cell.profilePhoto.layer.borderColor = UIColor.white.cgColor
cell.profilePhoto.layer.cornerRadius = cell.profilePhoto.frame.size.width / 2
cell.profilePhoto.clipsToBounds = true
PostUtils.loadPostImage(View: cell.postImage, PostId: post.getPostId())
return cell
}
这是我用来在 ImageView 中下载和设置图像的实用方法:
public static func loadPostImage(View postImage: UIImageView, PostId postId: String) {
let storage = Storage.storage()
let storageRef = storage.reference()
let photoRef = storageRef.child("photos/" + Auth.auth().currentUser!.uid + postId + ".jpg")
photoRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
postImage.image = nil
}
else {
let image = UIImage(data: data!)
postImage.image = image
}
}
}
【问题讨论】:
-
我使用的是同一个单元格,是的。我现在正在尝试对没有图片的帖子使用不同的单元格。
标签: ios swift uitableview autoresize heightforrowatindexpath