比较值并在uitableview中显示特定结果

时间:2016-01-14 13:03:11

标签: ios swift uitableview search filter

我正在尝试向我的UITableView添加搜索过滤器,当用户点击它时,我在导航栏“搜索”上有一个按钮,它会打开一个xib控制器,用户可以填写字段,之后完成UITableView应该只显示用户输入的比较结果。我已将xib中的所有值传递给tableviewcontroller,但如何比较它们并显示特定结果?

My xib view looks like this TableViewController

var pj = [PostedJobs]()
var pjJobs = PostedJobs()

class FeaturedTableViewController: UITableViewController {

    @IBAction func btnSearch(sender: UIBarButtonItem) {

        let detailViewController:SearchViewController = SearchViewController(nibName: "SearchViewController", bundle: nil)

        self.presentPopupViewController(detailViewController, animationType: MJPopupViewAnimationFade)
        // detailViewController.detailViewController1 = self

    }
    @IBOutlet var myTableView: UITableView!
    @IBOutlet weak var menuButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        println(sf.price)
        println(sf.deliveryTime)
        println(sf.distance)
        println(sf.featuredFilter)
        println(sf.location)
        println(sf.size)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "dismiss:", name:"dismiss", object: nil)

        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = "revealToggle:"

            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        var urlString = "http://ziprelay.com/api/public/index.php/api/allJobs?token=\(user.token)"
        let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        loadingNotification.mode = MBProgressHUDMode.Indeterminate
        loadingNotification.labelText = "Loading"

        let alert = UIAlertView()
        alert.title = "Alert"
        alert.addButtonWithTitle("okay")

        request(.POST, urlString)
            .responseJSON { request, response, data, error in

                println(user.token)
                println(data)
                println(response)
                println(request)

                MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

                if (error != nil) {
                    alert.message = String(stringInterpolationSegment: error?.localizedDescription)
                    alert.show()

                } else {
                    pj = [PostedJobs]()
                    for var i = 0; i < JSON(data!)["jobs"].count; i++ {
                        println(JSON(data!)["jobs"][0]["job_info"]["job_id"])
                        pj.append(PostedJobs.jobsPosted(data!,index: i))
                    }

                    println(pj.count)

                    self.myTableView.reloadData()
                    self.do_table_refresh()
                }
        }
    }

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

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return pj.count
    }

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

        var string:String = String()

        println(pj[indexPath.row].featured)

        if (pj[indexPath.row].featured == "null") {
            string = "reuseIdentifier"
        } else if (pj[indexPath.row].featured == "yes") {
            string = "reuseIdentifier1"
        }

        let cell = tableView.dequeueReusableCellWithIdentifier(string, forIndexPath: indexPath) as! FeaturedTableViewCell

        cell.lblHeading.text = pj[indexPath.row].parcel_type
        cell.lblFrom.text = pj[indexPath.row].from_zip
        cell.lblTo.text = pj[indexPath.row].to_zip
        // cell.lblSize.text = pj[indexPath.row].parcel_type
        cell.lblClientName.text = pj[indexPath.row].name
        var convertValue = String(stringInterpolationSegment: pj[indexPath.row].order_amount).floatValue

        cell.lblCost.text = "\(convertValue)"

        if(pj[indexPath.row].file_path != "")
        {
            ImageLoader.sharedLoader.imageForUrl("\(pj[indexPath.row].file_path)", completionHandler:{(image: UIImage?, url: String) in

                cell.imgProduct.image = image
            })
        }

        println(pj[indexPath.row].parcel_type)
        println(pj[indexPath.row].from_zip)
        println(pj[indexPath.row].to_zip)
        println(pj[indexPath.row].parcel_type)
        println(pj[indexPath.row].name)
        println(String(stringInterpolationSegment: pj[indexPath.row].order_amount))

        let favStar = UIImage(named: "favourites_star.png")

        switch pj[indexPath.row].rating {
        case 0:
            println("aeman")
        case 1:
            cell.star1.image = favStar
        case 2:
            cell.star1.image = favStar
            cell.star2.image = favStar
        case 3:
            cell.star1.image = favStar
            cell.star2.image = favStar
            cell.star3.image = favStar
        case 4:
            cell.star1.image = favStar
            cell.star2.image = favStar
            cell.star3.image = favStar
            cell.star4.image = favStar
        case 5:
            cell.star1.image = favStar
            cell.star2.image = favStar
            cell.star3.image = favStar
            cell.star4.image = favStar
            cell.star5.image = favStar
        default:
            println("aeman")
        }

        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 75
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let indexPathh = tableView.indexPathForSelectedRow()
        let currentCell = tableView.cellForRowAtIndexPath(indexPathh!) as UITableViewCell?;
        pjJobs.pathToPostedJobs = indexPathh!.row
        println(pjJobs.pathToPostedJobs)

        performSegueWithIdentifier("map", sender: self)
    }

    func do_table_refresh()
    {
        dispatch_async(dispatch_get_main_queue(), {
            self.myTableView.reloadData()
            return
        })
    }

    func dismiss(notification: NSNotification) {
        self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationFade)
    }
}

这是我的第一个应用程序,对于凌乱的代码感到抱歉,任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

请勿使用pj作为表格视图的来源。使用其他数组,当用户点击“完成”按钮时,循环遍历ng-class数组并仅将应该在表视图中的内容添加到第二个数组。然后将其用作表视图的源。

答案 1 :(得分:0)

您需要将传递的过滤数据用于UIViewController以过滤原始数组。

//as in your code pj is the full array
// definde a new array to be the dataSource
var dataSource:[PostedJobs]!

假设您有一个方法,当用户完成过滤并返回到表时将调用该方法,称为filterDate

func filterData() {
    let price = // the filtered price
    let loacation = // the filtered location
    let distance = // the filtered one
    let size = // the filtered one
    let time = // the filtered one
    let isFeatured = // the filtered one

   dataSource = jp.filter {
   $0.price == price && $0.location == location && $0.distance == distance &&  $0.size == size && $0.time.compare(time) == NSComparisonResult.OrderedSame && $0.isFeatured == isFeatured
  }
  // reload table 
  tableView.relaodData()

您将在所有dataSource方法中使用pj代替UITableViewDataSourceDelegate