MaNi ..
MaNi ..

Reputation: 1

Compare values and show specific result in uitableview

I am trying to add a search filter to my UITableView, I have a button on navigation bar "Search" when a user clicks it, it opens a xib controller and user can fill out the fields, after he's finished the UITableView should show only the compared result the user has entered. I have passed all the values from the xib to the tableviewcontroller, but how can I compare them and show specific result?

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)
    }
}

This is my first application, sorry about the messy code, Can anyone help ?

Upvotes: 0

Views: 584

Answers (2)

Ismail
Ismail

Reputation: 2818

You need to use the passed filtered data to the UIViewController to filter you original array.

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

lets say you have a method that will be called when the user finishes filtering and return back to the table, called 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()

and you will use dataSource instead of pj in all UITableViewDataSourceDelegate methods.

Upvotes: 0

lukasbalaz7
lukasbalaz7

Reputation: 400

Don't use pj as source of the table view. Use other array and when user taps on the "Done" button, loop through pj array and add only stuff that should be in the table view to the second array. Then use it as source of the table view.

Upvotes: 1

Related Questions