我从一个网址获取一些数据并尝试在我的表格视图中显示我有三个按钮名称用于排序。这是我的button action
方法:
@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
中的值进行排序?
已更新:
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()
答案 0 :(得分:3)
排序var arrDict: [BusinessData]
:
按商家名称
A-&GT; Z:
arrDict.sort({ $0.BusinessName < $1.BusinessName })
Z-&gt;一种:
arrDict.sort({ $0.BusinessName > $1.BusinessName })
评分
arrDict.sort({ $0.Rating < $1.Rating })
顺便说一下,按照惯例,Rating
和BusinessName
等变量名称应为小写。