簡體   English   中英

根據單元格增加 TableView 高度

[英]increase TableView height based on cells

我需要根據UITableViewCell內容大小增加UITableView高度。 我正在使用自定義 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
}

在我將所有地址動態存儲到 Address 數組后,我需要根據傳入的地址內容增加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 高度

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

更新

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

下面的代碼適用於具有 AutomaticDimension 的 UITableViewCell。

  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. 對於 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
}

解釋:

創建TableView單元格后,我們獲取即將顯示的單元格的邊框高度,並將單元格的高度添加到主TableView中。

無需設置和重置高度約束,您就可以根據其內容調整表格視圖的大小,如下所示:

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

在您的viewDidLoad寫:

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 高度約束的新 UIElement 並將其連接到視圖

@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)
        }

這應該可以解決問題。

我一直在努力使用滾動視圖,當加載表格視圖單元格時必須增加高度,並且表格視圖不應該是可滾動的,因為它應該顯示所有單元格(滾動由滾動視圖處理)。 無論如何,您應該使用 KeyValueObserver。 首先,您為高度約束創建出口:

 @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!

然后為表視圖添加觀察:

 private var tableViewKVO: NSKeyValueObservation?

之后,只需將 table view 添加到觀察中,並隨着內容大小的變化更改高度約束大小。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM