3

私のUITableView場合、メソッドを使用して最後のセルにスクロールします。

WLNetworkClient.sharedClient().createCommentWIthText(commentTextView.text, forItem: item) { error in

    defer {
        UIAlertController.showAlertFromError(error)
    }

    if error == nil {
        self.fetchedResultsController.fetchRequest.fetchLimit += 1
        try! self.fetchedResultsController.performFetch()
        self.tableView.reloadData()
        self.scrollTableViewToBottom()
    }
}

private func scrollTableViewToBottom() {

    tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: fetchedResultsController.fetchedObjects!.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}

しかし、これは期待どおりに機能しません.2番目のセルにいる場合でも常にテーブルが上からスクロールされるためです。これを修正する方法は?

4

5 に答える 5

8

dosdos answer はSwift 2で私のために働いた マイナーアップデートで追加

ivar を宣言する

var heightAtIndexPath = NSMutableDictionary()

関数 viewDidLoad() で

func viewDidLoad() {
  .... your code
  self.tableView.rowHeight = UITableViewAutomaticDimension
}

次に、次の 2 つのメソッドを追加します。

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
   let height = self.heightAtIndexPath.objectForKey(indexPath)
   if ((height) != nil) {
     return CGFloat(height!.floatValue)
   } else {
    return UITableViewAutomaticDimension
   }
 }

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
  let height = cell.frame.size.height
  self.heightAtIndexPath.setObject(height, forKey: indexPath)
}

スイフト 3:

var heightAtIndexPath = NSMutableDictionary()

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    let height = self.heightAtIndexPath.object(forKey: indexPath)
    if ((height) != nil) {
        return CGFloat(height as! CGFloat)
    } else {
        return UITableViewAutomaticDimension
    }
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let height = cell.frame.size.height
    self.heightAtIndexPath.setObject(height, forKey: indexPath as NSCopying)
}
于 2017-01-12T10:03:37.040 に答える
0

この問題については、次の記事で説明しています: UITableVIew が ReloadData を完了したことを確認するにはどうすればよいですか?

コードを次のように変更します。

self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.scrollTableViewToBottom()

layoutIfNeeded は、テーブルのリロードをすぐに強制します。すべてリンクで説明されています。

于 2015-09-09T10:08:38.970 に答える
0

問題は、tableViewの更新前にスクロールすることだと思います( by self.tableView.reloadData())。スクロールを遅らせてみてください:

     dispatch_async(dispatch_get_main_queue()) {
         self.scrollTableViewToBottom()
    }

または、tableView を強制的に更新します。

    self.tableView.reloadData()
    self.tableView.layoutIfNeeded()
    self.scrollTableViewToBottom()
于 2015-09-09T10:01:57.950 に答える