根据单元格中的内容自动更改单元格内容 - Xcode 9.2 Swift 4

时间:2018-03-15 04:02:16

标签: ios swift uitableview

我在视图控制器中有一个表视图,在单元格内,当文本太长时,我的文本会被切断。如何让单元格根据单元格中的内容自动更改,或者让文本换行以便文本不会被截断?这是我正在谈论的image

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50
}

func allowMultipleLines(tableViewCell: UITableViewCell) {
    tableViewCell.textLabel?.numberOfLines = 0
    tableViewCell.textLabel?.lineBreakMode = .byWordWrapping
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return courses.count
}


 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let course:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "course")!

    course.textLabel?.text = courses[indexPath.row]

    return course
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "Courses", sender: nil)
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let detailView: DetailCoursesViewController = segue.destination as! DetailCoursesViewController

    selectedRow = (table.indexPathForSelectedRow?.row)!

    detailView.setCourseTitle (t: courses[selectedRow])
    detailView.setCourseDescription (d: courseDescription[selectedRow])
    detailView.setCredits (c: credits[selectedRow])
    detailView.setPrerequisites (p: prereq[selectedRow])

}

以下是代码的image

3 个答案:

答案 0 :(得分:1)

1)在UILabel property numberOfLines = 0

cellForRowAt内设置UITableView

2)在ViewDidLoad内写下代码

self.tabelView.estimatedRowHeight = 44
self.tabelView.rowHeight = UITableViewAutomaticDimension

Demo Example

答案 1 :(得分:1)

首先,您需要在TableViewcell中为contentView设置标签的前导,尾随,底部和顶部约束

     override func viewDidLoad() {
        super.viewDidLoad()

        self.tabelView.estimatedRowHeight = 50
        self.tabelView.rowHeight = UITableViewAutomaticDimension

        // Do any additional setup after loading the view.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       // #warning Incomplete implementation, return the number of rows
       return courses.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let course:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "course")!
       cell.textLabel.numberOfLines = 0
       course.textLabel?.text = courses[indexPath.row]

       return course
    }

答案 2 :(得分:0)

1-在标签和单元格底部之间给出一个底部约束,如10

2-在函数tableView(_:cellForRowAt:)中执行以下操作:

cell.textLabel.numberOfLines = 0
cell.textLabel.lineBreakMode = .byWordWrapping