,可以通过以下步骤实现:
下面是一个示例代码:
import UIKit
class CustomCell: UITableViewCell {
var textView: UITextView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
textView = UITextView()
textView.isScrollEnabled = false
textView.font = UIFont.systemFont(ofSize: 14)
contentView.addSubview(textView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 8
textView.frame = CGRect(x: padding, y: padding, width: contentView.bounds.width - 2 * padding, height: contentView.bounds.height - 2 * padding)
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
var data: [String] = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium."]
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
view.addSubview(tableView)
}
// UITableViewDataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.textView.text = data[indexPath.row]
return cell
}
// UITableViewDelegate method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let text = data[indexPath.row]
let font = UIFont.systemFont(ofSize: 14)
let width = tableView.bounds.width - 16 // Assuming 8px padding on both sides
let height = text.height(withConstrainedWidth: width, font: font)
return height + 16 // Assuming 8px padding on top and bottom
}
}
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
}
这个示例代码演示了如何在具有最大高度动态高度的UITableViewCell中添加UITextView。UITextView会根据文本内容自动调整高度,并且单元格的高度也会根据UITextView的高度动态计算。你可以根据自己的需求进行修改和定制。
领取专属 10元无门槛券
手把手带您无忧上云