【问题标题】:IOS TableView not responding to last row codeIOS TableView 没有响应最后一行代码
【发布时间】:2017-09-18 20:39:03
【问题描述】:

我正在使用 swift 3 并有一个 TableView,当用户位于最后一行时,我是否试图触发一段特定的代码。出于某种原因,它完全忽略了这一点并且没有启动。我什至在那里放了一个断点,但它没有击中它。这就是我所拥有的

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

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

打印语句没有显示断点。我的 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
}

【问题讨论】:

    标签: ios swift uitableview swift3 uiscrollview


    【解决方案1】:

    您是否验证过willDisplay() 是否被调用?我怀疑不是。 func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath) 是一个 UITableViewDelegate 方法。在您设置它的委托属性之前,您的表格视图不会知道调用它,但我看不出这是在哪里完成的。

    可以在viewDidLoad() 中设置委托,就像您对dataSource 属性所做的那样:

    TableSource.delegate = self
    

    您还需要声明HomePageC 采用UITableViewDelegate 协议。这可以在类声明中完成:

    class HomePageC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    

    【讨论】:

    • 非常感谢,这正是我所缺少的,现在一切正常。
    【解决方案2】:

    尝试使用

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

    这是因为count返回数组中的项数,而索引路径返回的是从0开始的迭代

    【讨论】:

      【解决方案3】:

      您需要检查 self.Locations.count - 1 是否相等。由于索引从 0 开始,最后一项的 indexPath.row 将为 9,而 Locations.count 为 10。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        相关资源
        最近更新 更多