jap*_*ape 4 uitableview ios swift
在Swift中使用UITableView,有人可以帮我根据标签,图片和描述自动更改单元格的高度吗?
所有信息都正确传递,我只需要帮助格式化它.
我尝试使用它进行调整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
}
Run Code Online (Sandbox Code Playgroud)
为了使单元格自动变大,您需要做两件事:
tableView.rowHeight = UITableViewAutomaticDimension在你的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
}
Run Code Online (Sandbox Code Playgroud)
设置文本标签的宽度 然后调用此函数:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description)
return (heightOfRow + 60.0)
}
Run Code Online (Sandbox Code Playgroud)
对于基本单元格:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)
此功能不适用于自定义单元格.
如果单元格高度取决于图像高度,则返回图像高度+ someFloatValueAcordingToYourChoice.
希望它会奏效.
| 归档时间: |
|
| 查看次数: |
11646 次 |
| 最近记录: |