如何在表格视图中对A - z进行排序swift 2.0

时间:2016-03-28 10:22:43

标签: ios swift uitableview sorting

我有一个表视图,它将从一个url中删除json数据。它一切正常。我需要的是什么?在我的表格视图中,我有一个名为"名称标签"。它将在我的表格视图中显示名称。

我有一个菜单选项,一个名称叫"排序数据A - z"。当我点击它时,我的表视图数据应该重新加载,并从A-z字母顺序(我的名字标题)中排序日期。

这是我的按钮操作:

@IBAction func sortByAZBtnPress(sender: AnyObject) {
    }

我的 viewcontroller.swift

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var RightMenu: UIView!



    @IBOutlet weak var tableView: UITableView!   // UITable view declaration

    @IBOutlet weak var Resultcount: UILabel!     // count label

    var arrDict :NSMutableArray=[]   // array to store the value from json


    let cellSpacingHeight: CGFloat = 5  // cell spacing from each cell in table view


    override func viewDidLoad() {


        super.viewDidLoad()


        self.jsonParsingFromURL()  // call the json method

        let nib = UINib(nibName:"customCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")


        RightMenu.layer.borderWidth = 1



    }

    // web services method
    func jsonParsingFromURL () {
        let url = NSURL(string: "http://sampleUrl.com”)
        let session = NSURLSession.sharedSession()

        let request = NSURLRequest(URL: url!)
        let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            // print("done, error: \(error)")

            if error == nil
            {

                dispatch_async(dispatch_get_main_queue()){
                    self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray

                    //print(self.arrDict)

                    if (self.arrDict.count>0)
                    {
                        self.Resultcount.text = "\(self.arrDict.count) Results"
                        self.tableView.reloadData()
                    }}

                // arrDict.addObject((dict.valueForKey("xxxx")
            }


        }
        dataTask.resume()


    }




    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.arrDict.count
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }





    // calling each cell based on tap and users ( premium / non premium )
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


        let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell 


        cell.vendorName.text=arrDict[indexPath.section] .valueForKey("name") as? String 
        cell.vendorAddress.text=arrDict[indexPath.section] .valueForKey("address") as? String

        return cell 
    }


    // MARK:
    // MARK: Sort Method

    @IBAction func sortByRevBtnPress(sender: AnyObject) {

        self.indicator.startAnimating()
         self.indicator.hidden = false
         RightMenu.hidden = true

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()){
            self.indicator.stopAnimating()
            self.indicator.hidden = true


        };
        self.tableView.reloadData()


    }


    @IBAction func sortByAZBtnPress(sender: AnyObject) {
    }



}

请帮帮我。我没有明确的想法......谢谢

更新:

(
        {
        ad = 0;
        address = "900 York Mills Rd, Toronto, ON M3B 3H2, Canada";
        "category_id" = 1;

        latitude = "43.7563";
        longitude = "-79.3495";
        name = "Honeybee Restaurant";
        phone = 9876543210;
        rating = "5.0";
    },
        {
        ad = 1;
        address = "1677 Wilson Ave, Toronto, ON M3L 1A5, Canada";
        "category_id" = 1;

        latitude = "43.7194";
        longitude = "-79.5153";
        name = "Maki My Way";
        phone = 9875463254;
        rating = "4.0";
    },
        {
        ad = 1;
        address = "75 Bremner Blvd, Toronto, ON M5J 0A1, Canada";
        "category_id" = 1;

        latitude = "43.6429";
        longitude = "-79.3814";
        name = "Blow Fish Restaurant";
        phone = 9873245610;
        rating = "5.0";
    },
        {
        ad = 0;
        address = "4150 Yonge St, Toronto, ON M2P 2C6, Canada";
        "category_id" = 1;

        latitude = "43.747";
        longitude = "-79.4079";
        name = "SaigonFlower Restaurant";
        phone = 7892345621;
        rating = "3.0";
    },
        {
        ad = 1;
        address = "604 King St W, Toronto, ON M5V 1M6, Canada";
        "category_id" = 1;

        latitude = "43.6445";
        longitude = "-79.4004";
        name = "Sushi Gen";
        phone = 7456321065;
        rating = "2.0";
    },

)

3 个答案:

答案 0 :(得分:1)

要对tableview进行排序,您应先排序dataSource,然后重新加载tableview

在你的情况下:

首先按A到z排序:

  

arrDict

用于排序使用函数式编程:

arrDict = arrDict.sort({ $0.name > $1.name })

其次通过以下方式重新加载tableview:

  

self.tableView.reloadData()

答案 1 :(得分:1)

假设您的数组是一个字典数组,而您的字典有一个“Name”键,您可以执行此操作。如果您的dict具有包含名称的不同键,请更改代码。

@IBAction func sortByAZBtnPress(sender: AnyObject) {
   arrDict.sortUsingComparator { (dict1, dict2) -> NSComparisonResult in
       if let name1 = dict1["name"] as? String, name2 = dict2["name"] as? String {
              return name1.compare(name2)
       }
       return .OrderedAscending
   }
   self.tableView.reloadData()
}

对于按等级排序(从高到低),您可以使用此功能。

arrDict.sortUsingComparator { (dict1, dict2) -> NSComparisonResult in
    if let name1 = dict1["rating"] as? String, name2 = dict2["rating"] as? String {
        return name2.compare(name1)
    }
    return .OrderedAscending
}

答案 2 :(得分:0)

使用下面的代码arrDict

self.tableView.reloadData(): 进行排序
sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];