Ios 根据内容自动更改单元格高度-Swift
使用Swift中的UITableView,是否有人可以帮助我根据标签、图片和描述自动更改单元格高度 所有信息都正确传递,我只需要帮助格式化它 我尝试使用Ios 根据内容自动更改单元格高度-Swift,ios,swift,uitableview,Ios,Swift,Uitableview,使用Swift中的UITableView,是否有人可以帮助我根据标签、图片和描述自动更改单元格高度 所有信息都正确传递,我只需要帮助格式化它 我尝试使用cell.frame.size.height对其进行调整,但没有效果。我可以改变故事板中单元格的大小,但如果可能的话,我希望它更具动态性 提前谢谢你 我的手机号码如下: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexP
cell.frame.size.height
对其进行调整,但没有效果。我可以改变故事板中单元格的大小,但如果可能的话,我希望它更具动态性
提前谢谢你
我的手机号码如下:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Creator
let creator = self.photos[indexPath.row].creator
let user = UILabel()
user.frame = CGRectMake(self.headerView.frame.origin.x, self.headerView.frame.origin.y + self.headerView.frame.height + 3, self.view.frame.width, 12)
user.text = creator
cell.addSubview(user)
// Photo
let picture = self.photos[indexPath.row].image()
let imageView = UIImageView(image: picture!)
imageView.frame = CGRectMake(user.frame.origin.x, user.frame.origin.y + user.frame.height, self.view.frame.width, 400)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.addSubview(imageView)
// Photo description
let description = UITextView()
let des = self.photos[indexPath.row].photoDescription
description.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y + imageView.frame.height, self.view.frame.width, 65)
if des != nil {
description.text = des!
description.font = UIFont.systemFontOfSize(16)
description.editable = false
description.scrollEnabled = false
}
cell.addSubview(description)
cell.frame.size.height = user.frame.size.height + imageView.frame.size.height + description.frame.size.height + 30
return cell
}
为了使单元自动调整大小,您需要做两件事:
viewDidLoad
如果单元格高度取决于文本大小,请遵循以下步骤: 在ViewController.swift中添加该方法
func calculateHeight(inString:String) -> CGFloat {
let messageString = inString
let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
let requredSize:CGRect = rect
return requredSize.height
}
设置文本标签的宽度
然后调用此函数:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description)
return (heightOfRow + 60.0)
}
对于基本单元格:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
此函数不适用于自定义单元格
如果单元格高度取决于图像高度,则根据您的选择返回图像高度+SomeFloatValue
希望它能起作用。您需要了解自动布局以及单元格如何根据其内容和这些内容的自动布局约束调整其自身高度。单元格高度取决于文本大小或图像高度是多少?