2017-09-14 73 views
3

我用下面的代碼,以確定最後的畫面是在屏幕上向用戶可見可見:如何確定一個UITableView的最後一個單元格是屏幕

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
    if indexPath.row == collection.count - 1 { 
     print("last cell is seen!!") 
     print(cell.frame) 
    } 
} 

這部作品小屏幕,用戶必須滾動才能到達想要的單元格。但是,在整個表格可見的大屏幕上,此方法不起作用。有沒有什麼辦法可以確定屏幕底部到UITableView最後一個單元之間的距離?

任何幫助將不勝感激。謝謝。

編輯:這就是我想要完成的。

如果(最後一個單元是可見& &其大於100dp從屏幕底部){在屏幕上顯示的底部的固定按鈕}否則{添加按鈕的tableview的頁腳視圖,以便用戶可以向下滾動到按鈕}

+0

但是,爲什麼你想知道這一點? – Siyavash

+0

if(最後一個單元格可見&&它從屏幕底部超過100dp){在屏幕底部顯示一個固定按鈕} else {將按鈕添加到tableview的頁腳視圖,以便用戶可以向下滾動到按鈕} 是我需要這樣做的主要原因。感謝您的迴應。 –

+0

現在有意義了,請將其添加到問題中。也有你試着看着方法「didEndDisplaying」 – Siyavash

回答

1

我剛剛爲您創建了一個項目,向您展示一種可能的解決方案(有很多)。

基本上你只需要獲得最後一個單元格位置,使用

guard let lastCell = tableView.cellForRow(at: IndexPath(row: tableView.numberOfRows(inSection: 0)-1, section: 0)) else { 
    return 
} 

let lastCellBottomY = lastCell.frame.maxY 

然後知道的tableView的高度,你可以很容易地計算出最後一個單元格,並在屏幕的底部之間的距離:

let delta = tableHeight - lastCellBottomY 

,並檢查該距離足以讓你顯示或不固定的按鈕:

if delta > 55 { 
    // ...show button 
} else { 
    // ...hide button 
} 

對於動態按鈕(您想在用戶滾動時在tableView的最後一個單元格下面添加的按鈕),您可以添加一個帶有自定義單元格的新部分來表示按鈕。

您可以通過以下鏈接檢查出的整體思路:

https://www.dropbox.com/s/7wpwv6737efnt5v/ButtonTable.zip?dl=0

讓我知道如果您有任何疑問:)

1

您可以使用此方法來看看最後一個單元是可見或不可見

func isCellVisible(section:Int, row: Int) -> Bool { 
    guard let indexes = self.indexPathsForVisibleRows else { 
     return false 
    } 
    return indexes.contains {$0.section == section && $0.row == row } 
} } 

Source

然後,你可以這樣調用它

let lastCell = collection.count - 1 
let result = isCellVisible(section:"Your Section Number", row: lastCell) 
0

試試吧!希望能幫助你。

func scrollViewDidScroll(_ scrollView: UIScrollView) { 

    let contentOffsetMaxY: Float = Float(scrollView.contentOffset.y + scrollView.bounds.size.height) 
    let contentHeight: Float = Float(scrollView.contentSize.height) 

    let ret = contentOffsetMaxY > contentHeight - 100 
    if ret { 
     print("testButton is show"); 
    }else{ 
     print("testButton is hidden"); 
    } 
} 
相關問題