2017-04-21 31 views
0

我正在使用swift 3並有一個TableView,我想在用戶在最後一行時觸發一段特定的代碼。出於某種原因,它完全忽略了這一點,並沒有引發關注。我甚至在那裏放置了一個斷點,並沒有打到它。這是我IOS TableView沒有響應最後一行代碼

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 

     if indexPath.row == self.Locations.count { 
      print("Last Row") 
     } 
} 

print語句沒有顯示也不是斷點。我的TableView代碼是這樣的

class HomePageC: UIViewController,UITableViewDataSource { 

@IBOutlet weak var TableSource: UITableView! 
var Locations = [String]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    TableSource.allowsSelection = false 
    TableSource.dataSource = self 
    TableSource.estimatedRowHeight = 504 
    TableSource.showsVerticalScrollIndicator = false 
    TableSource.rowHeight = UITableViewAutomaticDimension 

    TableSource.tableFooterView = UIView() 

} 

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { 
    // This always returns 10 items 
    return Locations.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
    UITableViewCell { 
    // This just populates the fields as I have a custom TableView 
} 

回答

2

您是否驗證過是否調用了willDisplay()?我懷疑是不是。 func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath)是一種UITableViewDelegate方法。你的表視圖不會知道調用它,直到你設置它的委託屬性,但我不知道這是在做什麼。

代理人可以在viewDidLoad()進行設置,就像你正在做的dataSource屬性:

TableSource.delegate = self 

您還需要聲明的是HomePageC採用UITableViewDelegate協議。這可以在類聲明中完成:

class HomePageC: UIViewController, UITableViewDataSource, UITableViewDelegate { 
+0

非常感謝,正是我錯過的一切,現在一切正在進行。 –

1

您需要檢查對self.Locations.count - 1的平等。由於索引從0開始,最後一個項目的indexPath.row將是9,而Locations.count是10

 if indexPath.row == self.Locations.count - 1 { 
      print("Last Row") 
     } 
1

嘗試使用

if indexPath.row == (self.Locations.count - 1) { 
    print("Last Row") 
} 

其因計數返回項目的數組中的數,其中作爲索引路徑返回迭代,從0開始