如何从A-z对表格视图进行排序? [英] How to sort the table view from A-z?

查看:143
本文介绍了如何从A-z对表格视图进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个URL中获取一些数据,并尝试显示在我的表格视图中,因为我有三个用于排序的按钮名称.这是我的button action方法:

I am getting some data from one url and try to display in my table view In that I have three button name which is used to sort. Here is my button action method:

@IBAction func sortByAZBtnPress(sender: AnyObject) { }
@IBAction func sortByRatingBtnPress(sender: AnyObject){ }
@IBAction func sortByRecentBtnPress(sender: AnyObject){ }

这是我的bussinesstype.swift模型类:

import UIKit

class BusinessData {

    var BusinessName: String?
    var Address: String?
    var Rating: Float?
    var ContactNumber: String?

    init(json: NSDictionary) {
        self.BusinessName = json["business_name"] as? String
        self.Address = json["location"] as? String
        self.Rating = json["__v"] as? Float
        self.ContactNumber = json["phone_no"] as? String
    }
}

这是我的viewcontroller.swift:

import UIKit    

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {        
    var isTapped:Bool?   // cell tap checking bool        
    var selectedIndex:NSIndexPath?        
    @IBOutlet weak var RightMenu: UIView!        
    @IBOutlet weak var tableView: UITableView!   // UITable view declaration       
    var arrDict = [BusinessData]()   // array to store the value from json

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.jsonParsingFromURL()  // call the json method

        // nib for custom cell (table view)
        let nib = UINib(nibName:"customCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")            
        indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 90, 90))
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        indicator.center = self.view.center
        indicator.color = UIColor .redColor()
        self.view.addSubview(indicator)
    }

    override func viewWillAppear(animated: Bool) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "searchMethod:", name: "search", object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "endSearch", name: "endSearch", object: nil);
    }

    // web services method
    func jsonParsingFromURL ()
    {
        let url:NSURL = NSURL(string: "http://sample url/Fes?current_location=toronto&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18")!            
        if let JSONData = NSData(contentsOfURL: url)
        {
            if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary
            {
                if let reposArray = json["data"] as? [NSDictionary]
                {

                    for item in reposArray
                    {
                        let itemObj = item as? Dictionary<String,AnyObject>

                        let b_type = itemObj!["business_type"]?.valueForKey("type")                            

                        if (b_type as? String == "Taxis")
                        {                                
                            arrDict.append(BusinessData(json: item))                                
                        }
                    }
                }                    
            }
        }                    
    }

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

    // height for each cell
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        return cellSpacingHeight
    }

    // 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].BusinessName
            cell.vendorAddress.text = arrDict[indexPath.section].Address
            cell.VendorRating.rating = arrDict[indexPath.section].Rating!

        return cell
    }

    // 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)
    {
        RightMenu.hidden = true         
    }

    @IBAction func sortByRatingBtnPress(sender: AnyObject)
    {            
        RightMenu.hidden = true            
    }

    @IBAction func sortByRecentBtnPress(sender: AnyObject)
    {
        RightMenu.hidden = true        
    }
}

如何在表格视图business_name中对值进行排序?

How can I sort the values in my table view business_name?

已更新:

BusinessData.sortUsingComparator { (dict1, dict2) -> NSComparisonResult in        
    if let name1 = dict1["business_name"] as? String, name2 = dict2["business_name"] as? String
    {
        return name1.compare(name2)
    }        
    return .OrderedAscending
}
self.tableView.reloadData()

推荐答案

排序var arrDict: [BusinessData]:

按公司名称

A-> Z:

arrDict.sort({ $0.BusinessName < $1.BusinessName })

Z-> A:

arrDict.sort({ $0.BusinessName > $1.BusinessName })

通过评分

arrDict.sort({ $0.Rating < $1.Rating })

按照惯例,变量名称(例如RatingBusinessName)应小写.

By the way, by convention, variable names, such as Rating and BusinessName should be lowercase.

这篇关于如何从A-z对表格视图进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆