Ios 基于单元格增加TableView高度

Ios 基于单元格增加TableView高度,ios,iphone,swift,uitableview,Ios,Iphone,Swift,Uitableview,我需要根据UITableViewCell内容大小增加UITableView高度。 我正在使用自定义谷歌自动完成。我有一个UITextField。当我在UITextField中输入字母时,它将调用shouldChangeCharactersInrange委托方法 在该方法中,我将向Google AutoComplete API发送动态请求以获得预测结果 func textField(_ textField: UITextField, shouldChangeCharactersIn range:

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

在该方法中,我将向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
高度正在完美增加。我还需要增加tableView高度。

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

更新

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

无需设置和重置高度约束,即可根据表格视图的内容调整其大小,如下所示:

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

下面的代码适用于具有自动尺寸标注功能的UITableViewCell

  • 为tableViewHeight创建一个插座
  • 对于单元格的动态高度,我使用了以下代码:
  • 对于TableView的高度,使用TableView单元格的动态高度:
  • 说明:


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

    在您的
    视图加载中
    写入:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
        myTable.reloadData()
        myTable.layoutIfNeeded()
    }
    
    现在重写
    viewDidLayoutSubviews
    方法以提供tableview显式高度约束:

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

    这将确保加载tableview,并完成与约束相关的布局调整。

    为什么要增加tableview高度?让表格视图覆盖你的所有页面并设计其中的所有内容,它会自动滚动。我在self.view中有谷歌地图,在地图顶部有一个文本字段。如果我在tableview中只有一个单元格,那么我不希望表视图覆盖全视图控制器。在viewDidLoad中使用它,self.tableview.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];它在tableview页脚中创建UIView并隐藏地图。如果我将透明颜色设置为该视图,则地图不可单击/拖动。@DilipTiwari是否使用自动布局?是的,现在我通过接受高度约束解决了问题,并在返回单元格之前添加了这一行:-“tableViewHeightConstraint.constant=tableView.contentSize.height”感谢它的帮助,但在我的例子中,我对tableview使用了高度约束,因此我将tableview高度约束增加为TBLViewWheightConstraint.constant=tblView.contentSize.height。@DiiptiWari如何访问swift文件中的tableViewHeightConstraint。我是ios开发新手。有什么线索吗?@GauravArora您应该创建具有NSLayoutConstraints类型的tableViewHeightConstraint,它与具有自动尺寸的UITableViewCell一起工作?我试过了,但没用
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.estimatedRowHeight
    }
    
    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
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
        myTable.reloadData()
        myTable.layoutIfNeeded()
    }
    
    override func viewDidLayoutSubviews() {
        myTable.heightAnchor.constraint(equalToConstant:
        myTable.contentSize.height).isActive = true
    }