如何在 Table 视图的单元格中添加更多行?

How to add more lines in cells of Table View?

我用 Table View 做了一个应用程序,我放了一些单元格,但是在单元格中只有一行文本,我怎样才能使用更多行?

This is how it looks.

This is how is required to be.

这是我使用的代码:

import UIKit

@available(iOS 9.0, *)
class DuasViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

let tableList:[String] = ["Name", "Surname", "Date of Birth", "Place of Birth"]


@IBOutlet weak var myTableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.


    myTableView.reloadData()


    func allowMultipleLines(tableViewCell:UITableViewCell) {
        tableViewCell.textLabel?.numberOfLines = 10
        tableViewCell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
    }

    myTableView.reloadData()
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    var returnValue = 0

    returnValue = tableList.count

    return returnValue
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCellWithIdentifier("myCells", forIndexPath: indexPath)

    myCell.textLabel!.text = tableList[indexPath.row]
    return myCell
}  
}

所以我将如何添加更多的两行,并且行需要不同,例如:Name, Stevens, SteveSurname, My Surname Is, JobsDate of Birth, My Date of birth is, 01/01/2016.

感谢您的贡献。

UILabelnumberOfLines属性默认为1,设置为0允许无限行

所以在你的 cellForRowAtIndexPath 方法中你会有

myCell.textLabel!.numberOfLabels = 0

想要Surname, My Surname Is, Jobs分行,就得用换行符,也就是\n。你的字符串看起来像这样 Surname\nMy Surname Is\nJobs

对于新的 iOS 8,有一种新的方法可以使这个变得简单。

有一个新参数可以根据您的自动布局约束计算您的单元格高度。这是 UITableViewAutomaticDimension。您可以在视图控制器的 viewWillAppear 方法中使用它。

Objective C:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  self.tableView.estimatedRowHeight = 70.0; // for example. Set your average height 
  self.tableView.rowHeight = UITableViewAutomaticDimension;
  [self.tableView reloadData];
}

Swift:

override func viewWillAppear(animated: Bool) {
    self.tableView.estimatedRowHeight = 70 // for example. Set your average height 
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.reloadData()

} 

在你的榜样中表现得很好,如你所愿。至于我,我在 viewDidLoad 中添加了高度,而在 viewWillAppear 中仅保留了 reloadData()。还有有用的来源。

来自文档:rowHeight 的默认值是 UITableViewAutomaticDimension。我暂时保留代码,但请记住,您不需要在 iOS 8+.

中设置行高