Reputation: 4038
I have a custom tableview controller which has 3 sections.
1 first section has a collection view. Now I want to add text (which length is less than 1000 characters) to a first cell of 2nd section.
I plan to make that cell style basic, so I can add title.
cell.title.text = myString
?I mean I want something like
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView.section == 2 and cell == 1 {
cell.title.text = myString
return cell
}
}
myString
length is between 0 ~ 1000 words. How can I change the height of cell base on the length of myString
?Thanks
Upvotes: 0
Views: 92
Reputation: 1755
First set an identifier for the cell. If you're using storyboards, put a value in the Identifier field in the Attributes Inspector when the cell is selected.
Let's say you set that identifier to "basic"
. Then write something like the following code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 && indexPath.row == 0 {
// Section and row numbers start from 0, like practically everything else
// in Cocoa, so 1 is the second section, and 0 is the first row.
let cell = tableView.dequeueReusableCell(withIdentifier: "basic")! // Get a cell from the table view
cell.textLabel?.text = myString // Set the string
return cell
}
}
To allow the text field to increase in height when the string is long, just set the numberOfLines
property of the label in the cell to a large number (or a number that you calculate somehow based on the length of the string). For example, in the method above, before return cell
, insert this line:
cell.textLabel?.numberOfLines = 1000
The numberOfLines
property, according to its documentation, is the maximum number of lines to use for rendering text, so there shouldn't be anything wrong with setting it to a very large number. It will still resize based on the length of the string.
Upvotes: 1