根据细胞增加表观视图高度



我需要根据UITableViewCell内容大小来增加UITableView高度。我正在使用自定义的Google Auto完成。我有一个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
}

我将存储所有地址以动态地址数组,我需要根据传入的地址内容提高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!
}

UITableViewCell高度增长。我还需要增加表观高度。

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

 var frame = tableView.frame
 frame.size.height = tableView.contentSize.height
 tableView.frame = frame

update

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

以下代码对我有自动限度的UaiteViewCell。

  1. 为tableviewheight创建插座。
@IBOutlet weak var tableViewHeight: NSLayoutConstraint!
var tableViewHeight: CGFloat = 0  // Dynamically calcualted height of TableView.
  1. 对于单元格的动态高度,我使用了以下代码:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return tableView.estimatedRowHeight
}
  1. 对于表观视图的高度,桌面电视单元格的动态高度:
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
}

说明:

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

在您的 viewDidLoad中写:

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

现在覆盖viewDidLayoutSubviews方法以给出表观视图显式高度约束:

override func viewDidLayoutSubviews() {
    myTable.heightAnchor.constraint(equalToConstant:
    myTable.contentSize.height).isActive = true
}

这要确保加载了表观视图并进行了与任何约束相关的布局调整。

而无需设置和重置高度约束,您可以根据其内容来调整表图:

class DynamicHeightTableView: UITableView {
  override open var intrinsicContentSize: CGSize {
    return contentSize
  }
}

我一直在遇到滚动视图,当加载表视图单元格时,必须增加高度,而且表视图不应滚动,因为它应该显示所有单元格(通过滚动视图来处理滚动)。无论如何,您应该使用keyValueObserver。首先,您为高度约束创建出口:

 @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!

然后,您添加观察表以查看:

 private var tableViewKVO: NSKeyValueObservation?

之后,只需将表视图添加到观察和更改高度约束大小随着内容大小而变化。

 self.tableViewKVO = tableView.observe(.contentSize, changeHandler: { [weak self] (tableView, _) in
        self?.tableViewHeightConstraint.constant = tableView.contentSize.height
    })

这对我有用,非常简单的直截了当解决方案:

创建桌面高度约束的新效率,并将其连接到视图

@IBOutlet weak var tableViewHeightConst: NSLayoutConstraint!

然后在您创建单元格的任何地方添加以下内容,在我的情况下,我正在使用rxswift

 if self.tableView.numberOfRows(inSection: 0) > 0 {
            //gets total number of rows
            let rows = self.tableView.numberOfRows(inSection: 0)
            //Get cell desired height
            var cellHeight = 60
            self.tableViewHeightConst.constant = CGFloat(rows * cellHeight)
        }

这应该可以解决问题。

最新更新