【问题标题】:Swift tableView.reloadData() is not workingSwift tableView.reloadData() 不起作用
【发布时间】:2015-08-04 03:13:43
【问题描述】:

解决方案:https://stackoverflow.com/a/39638032/1106035

我是Swift 的新手,我需要在单击UIButton 操作时重新加载我的记录。对我来说,重新加载方法停止工作。我尝试了以下所有可能的方式:

这是我点击按钮时调用的函数

@IBAction func refresh(sender: AnyObject) {
    
    // I tried this one but doesn't works
    
    dispatch_async(dispatch_get_main_queue()) {
        self.tblNotes.reloadData()
    }
    
    // This one too doesn't works for me
        self.tblNotes.reloadData()
   
    //Neither this
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tblNotes.reloadData()
    })     

}

下面是我的整个班级

class ListaTrmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate , UISearchDisplayDelegate, EditNoteViewControllerDelegate {


@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tblNotes: UITableView!

var arrNotes: Array<CKRecord> = []
var editedNoteRecord: CKRecord!
var selectedNoteIndex: Int!

var searchActive : Bool = false
var filtered:Array<CKRecord> = []

var notesArray = [ListaTrmTableViewController]()


override func viewDidLoad() {
    super.viewDidLoad()
    
    tblNotes.delegate = self
    tblNotes.dataSource = self
    searchBar.delegate = self

        fetchNotes()
}

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

// MARK: - Table view data source

 func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    if(searchActive) {
        return filtered.count
    }
    
    return arrNotes.count
}
//Cell height size
 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 50.0
}

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedNoteIndex = indexPath.row
    performSegueWithIdentifier("viewControllerSg", sender: self)
}

//Segue to other ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "viewControllerSg" {
        let editNoteViewController = segue.destinationViewController as! ViewController
        
        if let index = selectedNoteIndex {
            editNoteViewController.editedNoteRecord = arrNotes[index]
        }
        if(searchActive){
            editNoteViewController.editedNoteRecord = filtered[selectedNoteIndex]
        }
    }
}

// Retrive data from CloudKit

func fetchNotes() {
  let container = CKContainer.defaultContainer()
    let privateDatabase = container.publicCloudDatabase
    let predicate = NSPredicate(value: true)
    
    let query = CKQuery(recordType: "Notes", predicate: predicate)
    query.sortDescriptors = [NSSortDescriptor(key: "Title", ascending: true)]
    
    privateDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
        if error != nil {
            println(error)
        }
        else {
            println(results)
            
            for result in results {
                self.arrNotes.append(result as! CKRecord)
            }
            
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.tblNotes.reloadData()
                self.tblNotes.hidden = false
            })
        }
    }
}


func didSaveNote(noteRecord: CKRecord, wasEditingNote: Bool) {
    if !wasEditingNote {
        arrNotes.append(noteRecord)
    }
    else {
        arrNotes.insert(noteRecord, atIndex: selectedNoteIndex)
        arrNotes.removeAtIndex(selectedNoteIndex + 1)
        selectedNoteIndex = nil
    }
    
    
    if tblNotes.hidden {
        tblNotes.hidden = false
    }
    
    tblNotes.reloadData()
}


 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("idCellNote", forIndexPath: indexPath) as! UITableViewCell
    
    if(searchActive){
        let noteRecord: CKRecord = filtered[indexPath.row]
        cell.textLabel?.text = noteRecord.valueForKey("Atitulo") as? String
    } else {
        let noteRecord: CKRecord = arrNotes[indexPath.row]
        cell.textLabel?.text = noteRecord.valueForKey("Atitulo") as? String
    }

    return cell
}

// Search functions

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    
    filtered = arrNotes.filter ({ (note) -> Bool in
        let titles = note.objectForKey("Atitulo") as? String
        //proceed as per normal
        let range = titles!.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        
        // I returned false to isolated the problem
        if let range = range { return true} else { return false}
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tblNotes.reloadData()
}

// The big problem is here

@IBAction func refresh(sender: AnyObject) {
    
    // I tried this one but don't works
    
    dispatch_async(dispatch_get_main_queue()) {
        self.tblNotes.reloadData()
    }
    // This one don't works too
        self.tblNotes.reloadData()
   
    //Neither this
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tblNotes.reloadData()
    })     

}

【问题讨论】:

  • 你的函数调用在哪里?我的意思是,你从哪里调用这个函数?
  • 尝试在 tableview 委托函数中放置一些断点。
  • 确保在 Storyboard 的 UItableview 连接部分设置了代理,否则它不会刷新...
  • 你检查过你的tblNotes是否为空吗?
  • @AshishKakkad 我在同一个视图控制器右侧导航栏中单击按钮刷新时调用此函数。

标签: ios swift uitableview


【解决方案1】:

首先,您需要确保已在您的 TableView 所在的 Storyboard 中设置委托和数据源。

其次,我认为您正在尝试重新加载由于网络问题而无法从 cloudkit 成功获取的数据。所以,tableView.reloadData() 不会给你带来任何东西,直到你从云中获取数据。所以,尝试在主线程中插入fetchNotes(),这样你的视图就会刷新。

@IBAction func refresh(sender: AnyObject) {
     dispatch_async(dispatch_get_main_queue()) {
          self.fetchNotes() 
     } 
}

【讨论】:

    【解决方案2】:

    您需要确保 View Controller 是 UITable 的委托和数据源。这可以通过情节提要完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多