What's the best way to have UITableView cell开发者_运维百科s with multiple lines ? Let's say 5.. or 6 ?
Instead of textLabel and la detailTextLabel ? Should I create a custom style ? or a custom view ?
Any tutorial / example is well accepted.
thanks
You can use the existing UILabel views in the UITableViewCell for this. The secret is to do the following:
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
By default, the UILabel only allows 1 line of text. Setting numberOfLines to 0 basically removes any limitations on the number of lines displayed. This allows you to have multiple lines of text.
The setting of the lineBreakMode to Word Wrap tells it to word wrap long lines of text onto the next line in the label. If you don't want this, you can skip that line.
You may also have to adjust the height of the table view cell as needed to make more room for the multiple lines of text you add.
For iOS 6.0 and later, use NSLineBreakByWordWrapping
instead of UILineBreakModeWordWrap
, which has been deprecated.
Since Swift 3:
func allowMultipleLines(tableViewCell: UITableViewCell) {
tableViewCell.textLabel?.numberOfLines = 0
tableViewCell.textLabel?.lineBreakMode = .byWordWrapping
}
There is a method to accomplish this just using storyboard. First, select the cell and go to the attributes section on the right panel. The first option should be 'Style'. Change this from custom to basic. Now, in your cell you should see text that says 'Title'. Double click it and in the right panel you should be able to set the number of lines.
cell.textLabel.numberOfLines = 0
together with
tableView.rowHeight = UITableView.automaticDimension
Does work but only if the number of lines is limited (2-3 lines).
What I had to do as well was embed the cell fields in a StackView
. That made all the difference. Now I can display as many lines as I want.
I found this worked for me on Xcode Version 8.0 (8A218a)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) UITableViewCell {
let cell = UITableViewCell()
//MARK: word wrapping in cell
cell.textLabel?.text = self.choices[(indexPath as NSIndexPath).row]
cell.textLabel?.numberOfLines=0 // line wrap
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
return cell
}
精彩评论