最简单的解决方案:Object-C
tableView.rowHeight = UITableViewAutomaticDimension;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = @"text";
cell.textLabel.numberOfLines = 0;
return cell;
}
也许你需要这样的东西。斯威夫特 3.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 50
tableView.frame = view.bounds
view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "some text ;)"
let cell: CustomTableViewCell
if let cel = tableView.dequeueReusableCell(withIdentifier: identifier) as? CustomTableViewCell {
cell = cel
} else {
cell = CustomTableViewCell(style: .default, reuseIdentifier: identifier)
}
cell.labelValue = "what u want"
return cell
}
}
你必须继承 UITableViewCell:
class CustomTableViewCell: UITableViewCell {
var labelValue: String? {
didSet { update() }
}
private let label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
install()
}
private func install() {
let padding: CGFloat = 6
label.textColor = .black
label.numberOfLines = 5
//label.font = Fonts.Default(.Normal).getFont(17, forDifferentDevice: false)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.7
label.lineBreakMode = .byTruncatingTail
label.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(label)
let cnt1 = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: padding)
let cnt2 = NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: padding)
let cnt3 = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: padding)
let cnt4 = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: padding)
contentView.addConstraints([cnt1, cnt2, cnt3, cnt4])
}
private func update() {
label.text = labelValue
}
}