2016-10-26 4 views
0

У меня проблема с установкой галочки для строки в представлении таблицы iOS Если я выберу один элемент выше, следующий 13-й элемент также будет выбран, я не уверен, почему?Multi select не работает должным образом в IOS

Должен ли я что-то делать со столом перед установкой галочки, потому что я просто проверяю одно условие, и если это условие истинно, я устанавливаю аксессуар типа как галочку, ниже - код.

Примечание: - Когда это произойдет, 13-я строка не будет выбрана, она просто изменит тип аксессуара этой строки.

if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
       if cell.selected { 
        if(self.sections[indexPath.section].files[indexPath.row].type != "cloud"){ 
         print(self.sections[indexPath.section].files[indexPath.row]) 
         cell.accessoryType = .Checkmark 
         NSNotificationCenter.defaultCenter().postNotificationName("enableOptions", object: nil) 
        } 
       } 
      } 

CellForIndexPath Код:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MyFilesTableViewCell 

     let fileSection = sections[indexPath.section] 
     let file = fileSection.files[indexPath.row] 

     cell.title.text = file.name 
     if file.timeStamp.isEmpty{ 
      cell.timeStamp.hidden = true 
     }else{ 
      cell.timeStamp.hidden = false 
      cell.timeStamp.text = file.timeStamp 
     } 
     cell.icon.image = file.icon 
     cell.actionsBtn.row = indexPath.row 
     cell.actionsBtn.section = indexPath.section 
     cell.actionsBtn.setTitle("\u{f142}", forState: .Normal) 
     cell.actionsBtn.addTarget(self, action: #selector(MyFilesTableViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) 
     if(editingTable){ 
      cell.actionsBtn.hidden = true 
     }else{ 
      cell.actionsBtn.hidden = false 
     } 
     if(file.type == "cloud"){ 
      cell.actionsBtn.hidden = true 
     } 
     cell.progressBar.progress = 0.0 
     cell.progressBar.hidden = true 
     return cell 
    } 
+0

Можете ли вы отправить код cellforrowatindexpath –

+0

Проблема здесь в том, что свойство повторного использования ячеек UITableView. Надеюсь, вы используете прототипы. Если да, дайте мне знать – KrishnaCA

+0

http://stackoverflow.com/questions/40057655/ios-swift-uiimageview-change-image-in-tableview-cell/40058685#40058685 см. Этот ответ @aoxi –

ответ

1

Его проблема с клеточной многоразовые в cellForRowAtIndexPath. Пожалуйста, используйте приведенный ниже код.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MyFilesTableViewCell 

cell.accessoryType = .None 

if cell.selected { 
       if(self.sections[indexPath.section].files[indexPath.row].type != "cloud"){ 
        print(self.sections[indexPath.section].files[indexPath.row]) 
        cell.accessoryType = .Checkmark 
       } 
      } 

let fileSection = sections[indexPath.section] 
let file = fileSection.files[indexPath.row] 

cell.title.text = file.name 
if file.timeStamp.isEmpty{ 
    cell.timeStamp.hidden = true 
}else{ 
    cell.timeStamp.hidden = false 
    cell.timeStamp.text = file.timeStamp 
} 
cell.icon.image = file.icon 
cell.actionsBtn.row = indexPath.row 
cell.actionsBtn.section = indexPath.section 
cell.actionsBtn.setTitle("\u{f142}", forState: .Normal) 
cell.actionsBtn.addTarget(self, action: #selector(MyFilesTableViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) 
if(editingTable){ 
    cell.actionsBtn.hidden = true 
}else{ 
    cell.actionsBtn.hidden = false 
} 
if(file.type == "cloud"){ 
    cell.actionsBtn.hidden = true 
} 
cell.progressBar.progress = 0.0 
cell.progressBar.hidden = true 
return cell 
} 
+0

ваш удивительный, спасибо вам большое :) это сработало. –

+0

@Aoxi - Спасибо. Его хорошо для разработчиков, чтобы иметь в виду, когда вы работаете с возможностью повторного использования в 'tableview' и' collectionview' в ios. Всегда присваивайте значения по умолчанию перед исходными значениями, и поэтому ячейки не будут сжиматься с различными концами массива или любой другой коллекции. –

0

Используя этот метод, вы можете пропустить ваши весь tableView reload и только изменить выбранное содержимое ячейки.

создать массив, хранить информацию о выбранном ряде ячейки

myArray:[Int] = [] 

В вашем методе cellForRowAtIndexPath установить

cell.actionsBtn.tag = indexPath.row 
myArray.insert(1, at: indexPath.row) 

вместо

cell.actionsBtn.row = indexPath.row` 

В вашем использовании buttonClicked(_:) метода как

func buttonClicked(sender: AnyObject) 
{ 

    let indexPath = IndexPath(row: sender.tag, section: 0) 
    let cell = tableView.cellForRow(at: indexPath) as! MyFilesTableViewCell 
    if myArray[sender.tag] == 1 
    { 
     cell.actionsBtn.setImage(UIImage(named:"checkmark_box"), for: .normal) 
     myArray[sender.tag] = 0 
    } 
    else 
    { 
     cell.actionsBtn.setImage(UIImage(named:"tick_mark"), for: .normal) 
     myArray[sender.tag] = 1 
    } 
} 
Смежные вопросы