2017-02-22 79 views
0

我知道调整UILabel高度和UITableViewCell可能是一个非常标准的问题,但我发现很多基于故事板和检查器的答案,但不是仅使用Swift 3.我创建了一个包含屏幕。该小区的高度被确定如下:如何通过编程调整uilabel和uitableviewcell高度?

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

我tableViewCell有一对夫妇在它的对象,一个UIImageView(MYIMAGE)和一个UILabel(会将myText),建立一个自定义类。定位和大小发生在cellForRowAt中。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell 
     cell.myImage.image = UIImage(named: "MyImage") 
     cell.myImage.layer.frame = CGRect(origin: CGPoint(x: 0, y: 10), size: (cell.myImage?.image?.size)!) 
     cell.myText.text = myArray[indexPath.row] 
     cell.myText.frame = CGRect(x: UIScreen.main.bounds.size.width * 0.25, y: 0, width: UIScreen.main.bounds.size.width * 0.7, height: 90) 
     cell.myText.numberOfLines = 0 
     return cell 
    } 

结果是一堆堆叠的单元格,彼此重叠。我应该如何调整UILabel框架的高度以适应myArray文本的数量,并调整单元格高度,使其至少达到myImage或myText的高度?

+0

你有使用autolayout吗? –

+0

http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights –

+0

我使用自动布局,并感谢链接到以前的问题。我错过了在另一个问题中以编程方式设置多个对象约束的例子。概念性地描述约束,例如引用updateConstraints(),或使用界面构建器显示。关于如何将UILabels,UIImageViews等对象绑定到单元格的contentView以及如何/何时调用updateConstraints,你有更多的解释吗? –

回答

0

您可以在Swift 3的表格视图中制作多行标签。

import UIKit 

     private let useAutosizingCells = true 

     class TableViewController: UITableViewController { 

      fileprivate let cellIdentifier = "Cell" 

      // MARK: - Lifecycle 

      override func viewDidLoad() { 
       super.viewDidLoad() 

       //setup initial row height here 
       if useAutosizingCells && tableView.responds(to: #selector(getter: UIView.layoutMargins)) { 
        tableView.estimatedRowHeight = 44.0 
        tableView.rowHeight = UITableViewAutomaticDimension 
       } 
      } 

    // MARK: - UITableViewDataSource 
    extension TableViewController { 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return detailsModel.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) 
     let details = detailsModel[indexPath.row] 

     cell.textLabel?.text = details.title 
     cell.detailTextLabel?.text = details.description 

     if useAutosizingCells && tableView.responds(to: #selector(getter: UIView.layoutMargins)) { 
      cell.textLabel?.numberOfLines = 0 
      cell.detailTextLabel?.numberOfLines = 0 
     } 

     return cell 
    } 

} 
+0

谢谢。我不明白为什么行数应该依赖于常量useAutosizingCells。从我迄今为止所了解到的情况来看,需要首先设置单元中对象的约束条件,将单元格的contentView绑定到标签的下边缘。我正在研究它是如何完成的。你有代码示例,你展示了如何做到这一点? –

相关问题