2014-10-27 15 views
13

Tôi là một tân binh hoàn chỉnh tại lập trình Swift và iOS, do đó bạn sẽ phải tha thứ cho câu hỏi có lẽ đơn giản.Thêm các phần, được phân tách theo ngày, thành UITableView trong Swift

Tôi đã tạo một bảngView hiển thị nội dung của một mảng (chuỗi) chỉ bằng cách nhấn một nút. Bây giờ, tôi muốn "nhóm" các chuỗi này trong các phần tableView, được sắp xếp theo ngày.

Cụ thể hơn: Khi người dùng chạm vào nút, chuỗi sẽ được chèn vào chỉ mục 0 của mảng và được hiển thị trong phần có tiêu đề của ngày đến ngày. Nếu có các giá trị cũ hơn ngày hôm nay trong mảng, các giá trị này sẽ được hiển thị trong một phần riêng biệt cho ngày đó. Mỗi phần phải tương ứng với một ngày 24 giờ và hiển thị tất cả các chuỗi được thêm vào trong ngày đó.

Dưới đây là một số mẫu mã của những gì tôi đã đạt được cho đến nay:

var testArray[String]() 
var sectionsInTable[String]() 

@IBOutlet weak var testTable: UITableView! 

@IBAction func saveButton(sender: AnyObject) { 

testArray.insert("\(strTest)", atIndex: 0) 
testTable.reloaddata() 

} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

    return sectionsInTable.count 

} 

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

    return testArray.count 

} 

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

    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") 

    cell.textLabel.text = String(testArray[indexPath.row])   

    return cell 
} 

Tôi thực sự không biết làm thế nào để quản lý phần phần. Hy vọng rằng ai đó có thể chỉ cho tôi đi đúng hướng. Cảm ơn!

Trả lời

17

Tôi thường làm điều này với Dữ liệu cốt lõi và NSFetchedResultsController vì nó có các phương pháp tích hợp để nhận các phần.

Tuy nhiên, tôi sẽ trả lời câu hỏi mà không sử dụng Dữ liệu cốt lõi. Mã này hơi lộn xộn hơn nhưng ở đây chúng tôi ...

Trước tiên, bạn phải tạo một đối tượng sẽ lưu trữ cả ngày và văn bản. TestArray sẽ là một mảng của các đối tượng này, thay vì một mảng String. Ví dụ:

class DateTextItem: NSObject { 
    var text: String = "" 
    var insertDate: NSDate = NSDate()  
} 

var testArray = [DateTextItem]() 

Sau đó, khi nút saveButton được nhấn, chúng tôi sẽ tạo và thêm đối tượng DateTextItem. Chúng tôi cũng sẽ thêm ngày vào các sectionInTable nếu nó chưa tồn tại.

@IBAction func saveButton(sender: AnyObject) { 
    let newItem = DateTextItem() 
    newItem.text = "Test \(testArray.count)" 

    // this is for development only 
    // increment the date after 2 records so we can test grouping by date 
    if testArray.count >= (testArray.count/2) { 
     let incrementDate = NSTimeInterval(86400*(testArray.count/2)) 
     newItem.insertDate = NSDate(timeIntervalSinceNow:incrementDate) 
    } 

    testArray.append(newItem) 

    // this next bit will create a date string and check if it's in the sectionInTable 
    let df = NSDateFormatter() 
    df.dateFormat = "MM/dd/yyyy" 
    let dateString = df.stringFromDate(newItem.insertDate) 

    // create sections NSSet so we can use 'containsObject' 
    let sections: NSSet = NSSet(array: sectionsInTable) 

    // if sectionsInTable doesn't contain the dateString, then add it 
    if !sections.containsObject(dateString) { 
     sectionsInTable.append(dateString) 
    } 

    self.tableView.reloadData() 
} 

Tiếp theo, tôi đã tạo hàm để lấy các mục trong một phần vì chúng tôi cần ở một vài nơi.

func getSectionItems(section: Int) -> [DateTextItem] { 
    var sectionItems = [DateTextItem]() 

    // loop through the testArray to get the items for this sections's date 
    for item in testArray { 
     let dateTextItem = item as DateTextItem 
     let df = NSDateFormatter() 
     df.dateFormat = "MM/dd/yyyy" 
     let dateString = df.stringFromDate(dateTextItem.insertDate) 

     // if the item's date equals the section's date then add it 
     if dateString == sectionsInTable[section] as NSString { 
      sectionItems.append(dateTextItem) 
     } 
    } 

    return sectionItems 
} 

Cuối cùng, đây là những gì các phương pháp Nguồn Bảng Chế độ xem mặc trông giống như

// MARK: - Table view data source 
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return sectionsInTable.count 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.getSectionItems(section).count 
} 

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

    // Configure the cell... 
    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") 

    // get the items in this section 
    let sectionItems = self.getSectionItems(indexPath.section) 
    // get the item for the row in this section 
    let dateTextItem = sectionItems[indexPath.row] 

    cell.textLabel.text = dateTextItem.text 

    return cell 
} 

// print the date as the section header title 
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return sectionsInTable[section] 
} 
+0

Cảm ơn bạn rất nhiều! Sẽ thử nó ngay lập tức và cho bạn biết nó hoạt động như thế nào. – maxpetter

+0

Mỗi khi bảng đang di chuyển - vòng lặp đang hoạt động và được khởi tạo mảng. Tôi không chắc đó là giải pháp tuyệt vời. Bạn cần phải chuẩn bị danh sách với các đối tượng một lần, và sau đó sử dụng nó. –

0

Bạn cần phải thực hiện một mảng cho mỗi ngày (gọi là dayArray [] ví dụ) và thêm nó vào sectionInTable [] và làm điều gì đó như thế:

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

    return sectionsInTable.count 

} 

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

    return sectionsInTable.objectAtIndex(section).count 

} 

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

    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") 

    cell.textLabel.text = String(sectionInTable.objectAtIndex(indexPath.section).objectAtIndex(indexPath.row))   

    return cell 
} 

Xin lỗi nếu tôi đã làm sai lầm, tôi không quen thuộc với nhanh nhưng tôi nghĩ ý tưởng có thể giúp ích.

+0

nơi là phương pháp để thêm tiêu đề trong phần – SARATH

17

Tôi đang cần một cái gì đó tương tự, và trong khi Ron Fessler 's giải pháp hoạt động, khi có rất nhiều bộ phận/các hàng, phải mất một thời gian rất dài để bảng tải dữ liệu, và thậm chí sau đó nó không đáp ứng được nhiều. Vấn đề chính ở đây tôi nghĩ là chức năng getSectionItems vì nó sẽ luôn đi qua tất cả các mục ...

Giải pháp của tôi: phương pháp dataSource

struct TableItem { 
    let title: String 
    let creationDate: NSDate 
} 

var sections = Dictionary<String, Array<TableItem>>() 
var sortedSections = [String]() 

@IBAction func saveButton(sender: AnyObject) { 

    let date:String = "your date in string..." 

    //if we don't have section for particular date, create new one, otherwise we'll just add item to existing section 
    if self.sections.indexForKey(date) == nil { 
     self.sections[date] = [TableItem(title: name, creationDate: date)] 
    } 
    else { 
     self.sections[date]!.append(TableItem(title: name, creationDate: date)) 
    } 

    //we are storing our sections in dictionary, so we need to sort it 
    self.sortedSections = self.sections.keys.array.sorted(>) 
    self.tableView.reloadData() 
} 

tableView:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return sections.count 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return sections[sortedSections[section]]!.count 
} 

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

    var cell = tableView.dequeueReusableCellWithIdentifier("Cell")   

    let tableSection = sections[sortedSections[indexPath.section]] 
    let tableItem = tableSection![indexPath.row] 

    cell.titleLabel?.text = tableItem.title 

    return cell 
} 

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return sortedSections[section] 
} 
+0

Đây là một giải pháp đơn giản, dễ thực hiện trên một TableView hiện có. Cảm ơn nhiều. – tonyedwardspz

+0

tôi tiếp tục nhận được lỗi tạm thời: Chỉ mục ra khỏi phạm vi khi tôi sử dụng [section] trong ủy quyền tabelview? – Skovie

+0

@Skovie kiểm tra xem 'phần' có nằm trong phạm vi' các phần được sắp xếp' trước 'trả về' hay không. Ví dụ: 'if section

Các vấn đề liên quan