2015-06-01 2 views
0

У меня есть UITableView с несколькими вариантами, включенными с галочками. Когда я делаю выбор, все видимые в представлении, я не сталкиваюсь с ошибками. Однако, если я прокручу вниз и поместив выбранный элемент из поля зрения, я получаю ошибки, и, несмотря на то, что строка остается выбранной, галочка исчезает.UITableView, выходящий из поля зрения

import Foundation 

импорт Разбираем импорт UIKit

класс customerMenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var menuTV: UITableView! 

var menuItems: [String] = ["Hello"] 
var menuPrices: [Double] = [0.0] 
var orderSelection: [String] = [] 
var priceSelection: [Double] = [] 

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

{ 
    return menuItems.count 

} 

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

    return 1; 
} 


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

{ 
    let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell") 

    cell.textLabel!.text = "\(menuItems[indexPath.row])\t $\(menuPrices[indexPath.row])" 

    return cell 

} 
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    //tableView.deselectRowAtIndexPath(indexPath, animated: true) 
    let cell = tableView.cellForRowAtIndexPath(indexPath) 
    cell!.accessoryType = .Checkmark 
    orderSelection.append(cell!.textLabel!.text!) 
} 
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    let cell = tableView.cellForRowAtIndexPath(indexPath) 
    cell!.accessoryType = .None 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    menuTV.allowsMultipleSelection = true 
    let resMenu = resUser.sharedInstance 
    var resName = resMenu.nameStr 
    var resID = resMenu.idStr 



      var menuQ = PFQuery(className: "menu") 
      menuQ.getObjectInBackgroundWithId(resID){ 
       (menus: PFObject?, error: NSError?) -> Void in 
       if error == nil && menus != nil { 
        let items: [String] = menus?.objectForKey("menuItems") as! Array 
        let prices: [Double] = menus?.objectForKey("menuPrices") as! Array 
        self.menuItems = items 
        self.menuPrices = prices 
        self.menuTV.reloadData() 
     } 

    } 

} 



@IBAction func continueButton(sender: AnyObject) { 


    let selections = menuTV.indexPathsForSelectedRows() as! [NSIndexPath] 
    var indexCount = selections.count 
    println(indexCount) 
    var x = 0 
    while x < indexCount 
    { 
     println(x) 
     let currentCell = menuTV.cellForRowAtIndexPath(selections[x]) as? UITableViewCell?; 
     println(x) 
     println(selections[x].row.description) 
     orderSelection.append(currentCell!!.textLabel!.text!) 
     println(orderSelection[x]) 
     x++ 
    } 



} 



override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

ответ

0

Это как вид таблицы работы.

Когда ячейки прокручиваются за пределы экрана, он попадает в очередь на переработку, а затем снова используется для отображения данных для другого indexPath в ваших данных.

Каждый раз, когда пользователь вносит какие-либо изменения в данные для ячейки, вы должны сохранить ее в своей модели данных (обычно это массив информации или массив массивов, если вы используете разделенное представление таблицы). Затем вы должны сообщить в виде таблицы, чтобы отобразить измененную ячейку. Метод cellForRowAtIndexPath подбирает измененные данные и показывает изменения в ячейке. Если ячейка прокручивается за пределы экрана, а затем прокручивается назад на экране, она отображается с правильными настройками.

Это относится к отслеживанию того, какие ячейки также выбраны.

+0

правильно, поэтому я могу сохранить данные в массиве, но это вызывает много осложнений, когда что-то отменено. Как точно я бы закодировал cellForRowAtIndexPath, чтобы сохранить выбранные данные, даже когда их отвлекло от вида? –

Смежные вопросы