Scroll上的iOS TableView索引值

时间:2016-09-30 07:57:18

标签: ios swift tableview indexpath

我在Swift项目中使用表视图。问题是表视图单元索引路径值。最初加载表时,索引值是可以的。但是当我滚动表格视图时,单元格索引路径会发生变化,而我从数据数组中获取的ID是错误的。谷歌搜索结果是因为可重复使用的细胞之类的东西。这是我的视图控制器代码:

//
//  ProjectsController.swift
//  PMUtilityTool
//
//  Created by Muhammad Ali on 9/23/16.
//  Copyright © 2016 Genetech Solutions. All rights reserved.
//

import UIKit

class ProjectsController: UIViewController {

    //MARK: Properties
    var ProjectsArray: Array<Project> = []

    @IBOutlet weak var ProjectsTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.navigationController?.navigationBarHidden = true

        // Remove indenting of cell
        if self.ProjectsTableView.respondsToSelector(Selector("setSeparatorInset:")) {
            self.ProjectsTableView.separatorInset = UIEdgeInsetsZero
        }
        if self.ProjectsTableView.respondsToSelector(Selector("setLayoutMargins:")) {
            self.ProjectsTableView.layoutMargins = UIEdgeInsetsZero
        }

        self.ProjectsTableView.layoutIfNeeded()

        // Get projects
        getProjects()
    }

    override func viewWillAppear(animated: Bool) {
        self.navigationController?.navigationBarHidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

    // MARK: - TableView Datasource
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.ProjectsArray.count
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // print("clicked")
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> ProjectTableViewCell {

        print(indexPath.row)

        let cell = tableView.dequeueReusableCellWithIdentifier("ProjectViewCell", forIndexPath:indexPath) as! ProjectTableViewCell

        // Remove indenting of cell
        cell.separatorInset = UIEdgeInsetsZero
        cell.layoutMargins = UIEdgeInsetsZero

        // Set project name
        cell.ProjectName.text = "\((indexPath.row)+1). \(self.ProjectsArray[indexPath.row].ProjectName)"

        // Set action button
        cell.ActionButton.tag = indexPath.row
        cell.ActionButton.addTarget(self, action: #selector(ProjectsController.projectActions(_:)), forControlEvents: .TouchUpInside)

        return cell

    }

    func reloadTableViewAfterDelay()
    {
        ProjectsTableView.performSelector(#selector(UITableView.reloadData), withObject: nil, afterDelay: 0.1)
    }

    @IBAction func projectActions(sender: UIButton) {
        let index = sender.tag

        let optionMenu = UIAlertController(title: nil, message: self.ProjectsArray[index].ProjectName, preferredStyle: .ActionSheet)

        // Report Progress
        let reportProgressAction = UIAlertAction(title: "Report Progress", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            self.performSegueWithIdentifier("ShowReportProgress", sender: sender)
        })

        // Cancel
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
            (alert: UIAlertAction!) -> Void in

        })

        optionMenu.addAction(reportProgressAction)
        optionMenu.addAction(cancelAction)

        self.presentViewController(optionMenu, animated: true, completion: nil)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if let button = sender where segue.identifier == "ShowReportProgress" {
            let upcoming: ReportProgressController = segue.destinationViewController as! ReportProgressController
            print(self.ProjectsArray[button.tag].ProjectId)
            upcoming.ProjectId = self.ProjectsArray[button.tag].ProjectId
            upcoming.ProjectName = self.ProjectsArray[button.tag].ProjectName
        }

    }

    // MARK: Get Projects Function
    func getProjects() -> Void
    {

        var params = Dictionary<String,AnyObject>()
        params =  ["user_id":CFunctions.getSession("id")]

        WebServiceController.getAllProjects(params){ (type, response, message) -> Void in

            if (type == ResponseType.kResponseTypeFail)
            {

                // Show Error
                let alert = UIAlertController(title: "Error(s)", message:"Unable to load projects.", preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                self.presentViewController(alert, animated: true){}

            }
            else
            {
                //debugPrint(response)

                if(response.count>0)
                {
                    self.ProjectsArray = response
                }
                else
                {
                    // Show Error
                    let alert = UIAlertController(title: "Error(s)", message:"No projects found.", preferredStyle: .Alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                    self.presentViewController(alert, animated: true){}
                }

                self.reloadTableViewAfterDelay()

            }
        }
    }

}

无论我向下滚动还是向上滚动,我希望每个单元格的索引值都保持不变。

4 个答案:

答案 0 :(得分:1)

例如,在iPhone屏幕中,您可以一次看到5个单元格。

  1.   

    所以,第一次,当你加载tableView时,将首先调用cellForRowAtindexPAth方法   细胞

    “正如您所提到的,第一次加载和tableView索引 是的。“

  2.   

    现在向下滚动时,将调用cellForRowAtIndexPath方法   只有6和7。

    “直到这一次,一切正常,正如你所提到的。你可以看到整体索引路径为完整1,2, 3,4,5,6,7 。”

    *屏幕上当前可以看到暗区。

  3.   

    现在向上滚动 {2 cells} 。现在您可以看到屏幕上当前的可见单元格 1,2,3,4,5

  4.   

    这里,将仅为编号为2,1的单元格调用cellForRowAtIndexPath方法。

    因为您的屏幕已经加载/显示了单元格编号3,4,5。

    因此,您的打印日志将是1,2,3,4,5,6,7,2,1。

答案 1 :(得分:0)

您应该在课程中添加UITableViewDelegateUITableViewDataSource。并在ProjectsTableView.delegate = self中设置viewDidLoad

答案 2 :(得分:0)

您需要使用tableViewCell的层次结构来获取按钮的indexPath。

 @IBAction func projectActions(sender: UIButton) {
  let button = sender as! UIButton
  let view = button.superview!
  let cell = view.superview as! UITableViewCell
  let indexPath = self.reloadTableViewAfterDelay.indexPathForCell(cell)
  let index = indexPath.row
}

 if let button = sender where segue.identifier == "ShowReportProgress" {
       let upcoming: ReportProgressController =  segue.destinationViewController as! ReportProgressController
       let view = button.superview!
       let cell = view.superview as! UITableViewCell
       let indexPath = self.reloadTableViewAfterDelay.indexPathForCell(cell)
       let index = indexPath.row
       print(self.ProjectsArray[index].ProjectId)
       upcoming.ProjectId = self.ProjectsArray[index].ProjectId
       upcoming.ProjectName = self.ProjectsArray[index].ProjectName
       }

答案 3 :(得分:0)

需要使用tableViewCell获取按钮的indexPath,而不是使用下面的代码

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellId: NSString = "Cell"
    let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId as String)! as UITableViewCell

    let ActionButton : UIButton = cell.viewWithTag(10) as! UIButton

    ActionButton.addTarget(self, action: #selector(ViewController.projectActions(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    return cell
}

@IBAction func projectActions(sender: UIButton) {
    let buttonPosition = sender.convertPoint(CGPointZero, toView: self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(buttonPosition)
    print(indexPath?.row)

}