简体   繁体   中英

custom tableview controller's cell text

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.

  1. How can I call 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
    }
}
  1. because myString length is between 0 ~ 1000 words. How can I change the height of cell base on the length of myString ?

Thanks

First Question

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
    }
}

Second Question

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM