2016-10-28 9 views
0

Я пытался выяснить, как это решить, и я смог удалить любую строку, но поскольку я не знал, как удалить выбранную строку из своих данных userdefault, она просто исчезла временно. Я создал экземпляр с именем sections, который содержит sectionName и words. Я хотел бы получить доступ к словам и удалить выбранный по строкам в UITableView. Также есть ошибка. Ошибка говорит Type [String]! не имеет подписчиков. Кажется, что есть проблема с этой линией;Как удалить данные userdefault в строках в разделе в Swift?

removeData(index: sections[indexPath.section].words[indexPath.row]) 

И вот этот код в следующем;

struct Section { 
    var sectionName: String! 
    var words: [String]! 

    init(title: String, word: [String]) { 
     self.sectionName = title 
     self.words = word 

    } 
} 
var sections = [Section]() 
     sections = [ 
     Section(title: "A", word: []), // 1 
     Section(title: "B", word: []), //2 
     Section(title: "C", word: []), 
     Section(title: "D", word: []), 
     Section(title: "E", word: []), 
     Section(title: "F", word: []), 
     Section(title: "G", word: []), 
     Section(title: "H", word: []), 
     Section(title: "I", word: []), 
     Section(title: "J", word: []), 
     Section(title: "K", word: []), 
     Section(title: "L", word: []), 
     Section(title: "M", word: []), 
     Section(title: "N", word: []), 
     Section(title: "O", word: []), 
     Section(title: "P", word: []), 
     Section(title: "Q", word: []), 
     Section(title: "R", word: []), 
     Section(title: "S", word: []), 
     Section(title: "T", word: []), 
     Section(title: "U", word: []), 
     Section(title: "V", word: []), 
     Section(title: "W", word: []), 
     Section(title: "X", word: []), 
     Section(title: "Y", word: []), 
     Section(title: "Z", word: []) 
    ] 




func getData() -> [String] { 
    if let data = userdefaultData.stringArray(forKey: "data") { 

     return data 
    } 
    return [] 
} 


func removeData(index: Int) { 
    var data = getData() 
    data.remove(at: index) 
    userdefaultData.set(data, forKey: "data") 
} 

// Override to support editing the table view. 
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 

    if editingStyle == .delete { 
     // Delete the row from the data source 

     tableView.beginUpdates() 

     // Delete the row from the data source 
     if getData().count > 0 { 
      removeData(index: sections[indexPath.section].words[indexPath.row]) 
     } 

     tableView.deleteRows(at: [indexPath], with: .fade) 

     tableView.endUpdates() 



    } else if editingStyle == .insert { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    } 
} 
+0

добавить одну строку после изменений в вашем Nsuedefault, что userDefaults.synchronize() –

+0

Ошибка говорит Тип [String]! не имеет подписчиков. Кажется, что есть проблема с этой линией; removeData (index: sections [indexPath.section] .words [indexPath.row]) – Ryo

+0

похоже, что вы передаете строку функции, которая принимает int? разделы [indexPath.section] .words [indexPath.row] должны возвращать строку –

ответ

0

Как я вижу, вы пытаетесь удалить данное слово из своих данных. Я бы рекомендовал сделать следующее:

Сначала найдите слово, которое хотите удалить, getData.count > 0 Заявления тела.

if getData().count > 0 { 
     let section = sections[indexPath.section 
     let word = section.words[indexPath.row] 
     remove(word) 
} 

Чем заменить функцию removeData с помощью этой функции:

func remove(_ word: String) { 
    var data = getData() 

    // Lets search for the removeable word's index in the array 
    var index = 0 
    for wordCandidate in data { 
     if wordCandidate == word { 
      // Once found, exit from the loop 
      return 
     } 
     // if not found, increase the index by one 
     index += 1 
    } 
    // Remove the word at the right index 
    data.remove(at: index) 
    userdefaultData.set(data, forKey: "data") 
} 

Надеется, что это помогает!

+0

Спасибо, но ошибка указала неверное количество строк в разделе 5. Количество строк, содержащихся в существующем разделе после обновления (1), должно быть равно количеству строк, содержащихся в этом разделе, перед обновлением (1) плюс или минус количество строк, вставленных или удаленных из этого раздела (0 вставлено, 1 удалено) и плюс или минус количество строк, перемещенных в или из этого раздела (0 перемещен, 0 перемещен). ' – Ryo

+0

это сбой, потому что вам нужно также обновить источник данных tableView. посмотрите, как это сделать: http://stackoverflow.com/questions/8306792/uitableview-reload-section – dirtydanee

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