根据单元格增加TableView高度

Vim*_*.M. 7 iphone uitableview ios swift

我需要UITableView根据UITableViewCell内容大小增加高度.我正在使用自定义Google自动完成功能.我有一个UITextField.当我输入一个字母时,UITextField它将调用shouldChangeCharactersIn范围委托方法.

在该方法中,我将向Google AutoComplete API发送动态请求以获取预测结果.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if tableView.numberOfRows(inSection: 0) > 0
    {

    let newLength = (textField.text?.characters.count)! + string.characters.count - range.length
    let enteredString = (textField.text! as NSString).replacingCharacters(in: range, with:string)

    if newLength == 0 {
        tableView.isHidden = true
    }

    if newLength > 0
    {
        address.removeAll()
        self.tableView.isHidden = false

        GetMethod("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=\(enteredString)&key=MYAPIKEY", completion: { (resultDict) in

            let resultArray = resultDict.object(forKey: "predictions")! as! NSArray

            print(resultArray.count)

            for temp in resultArray

            {
                 let newtemp = temp as! NSDictionary
                 let tempAdd = newtemp.value(forKey:"description") as! String
                let placeId = newtemp.value(forKey:"place_id") as! String
                var dict = [String : AnyObject]()
                dict["address"] = tempAdd as AnyObject?
                dict["latlong"] = placeId as AnyObject?
                self.address.append(dict as AnyObject)
                 print(newtemp.value(forKey:"description"))
                 print(self.address.count)
                self.tableView.reloadData()

            }

        })
      }
    return true
}
Run Code Online (Sandbox Code Playgroud)

在我将所有地址动态存储到地址数组后,我需要UITableView根据传入的地址内容增加高度.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "TableViewCell"
    var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
    if cell == nil
    {
    cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
    }

    let addresstoDisp  = address[indexPath.row] as! NSDictionary
    let name = addresstoDisp.value(forKey: "address")
    cell?.textLabel?.numberOfLines = 0
    cell?.translatesAutoresizingMaskIntoConstraints = false

    cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
    cell?.textLabel?.textAlignment = NSTextAlignment.center
    cell?.textLabel?.text = name as! String

    return cell!
}
Run Code Online (Sandbox Code Playgroud)

UITableViewCell身高正在增加.另外我需要增加tableView高度.

Raj*_*r R 17

在创建单元格后添加这些行.因为它在viewDidLoad()中返回0高度

 var frame = tableView.frame
 frame.size.height = tableView.contentSize.height
 tableView.frame = frame
Run Code Online (Sandbox Code Playgroud)

UPDATE

//After Tableviews data source values are assigned
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true
Run Code Online (Sandbox Code Playgroud)

  • 谢谢它帮助了我,但在我的情况下,我对 tableview 使用高度约束,所以我将 tableview 高度约束增加为 tblViewHeightConstraint.constant = tblView.contentSize.height。 (2认同)

Aka*_*rma 6

下面的代码对我来说适用于具有AutomaticDimension的UITableViewCell。

  1. 为 tableViewHeight 创建一个出口。
@IBOutlet weak var tableViewHeight: NSLayoutConstraint!
var tableViewHeight: CGFloat = 0  // Dynamically calcualted height of TableView.
Run Code Online (Sandbox Code Playgroud)
  1. 对于单元格的动态高度,我使用了以下代码:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return tableView.estimatedRowHeight
}
Run Code Online (Sandbox Code Playgroud)
  1. 对于 TableView 的高度,以及 TableView 单元格的动态高度:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print(cell.frame.size.height, self.tableViewHeight)
    self.tableViewHeight += cell.frame.size.height
    tableViewBillsHeight.constant = self.tableViewHeight
}
Run Code Online (Sandbox Code Playgroud)

解释:

创建TableView单元格后,我们获取即将显示的单元格的框架高度并将单元格的高度添加到主TableView中。