ios - Swift TableView 重新加载但单元格在单击之前保持不变

标签 ios uitableview swift uisegmentedcontrol

Swift 中,我使用 Segmented Controller 使用 JSON 填充我的 TableView,基于选择哪个段。两个 JSON 文件都加载成功,因为我的第一个有两个单元格,第二个有 3 个。当我单击第二个部分时,在当前查看的两个单元格下方,会出现第三个。问题是尽管我的 self.tableView .reloadData() 在我的 Segmented ControllerIBAction 中调用了上面的两个,但它不会重新加载和我的 viewWillAppear 功能。

单击单元格后,相应的信息会自行显示,一切正常,但直到我单击该行时才会出现。给了什么?

我的 MainVC.swift 文件

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!
    var dataArray: NSArray = NSArray()

    @IBOutlet var Controller: UISegmentedControl!

    override func viewWillAppear(animated: Bool) {
        self.tableView .reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        startConnectionAt("http://www.domain.com")
        // Do any additional setup after loading the view.
    }

    @IBAction func Change(sender: AnyObject) {

        if Controller.selectedSegmentIndex == 0 {
            startConnectionAt("http://www.domain.com")
        }
        else if Controller.selectedSegmentIndex == 1 {
            startConnectionAt("http://www.domain.com")
        }

        self.tableView .reloadData()

    }

//MARK: JSON Loading

    var data: NSMutableData = NSMutableData()
    func startConnectionAt(urlPath: String){
        var url: NSURL = NSURL(string: urlPath)
        var request: NSURLRequest = NSURLRequest(URL: url)
        var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
        connection.start()
    }

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        println("Connection failed.\(error.localizedDescription)")
    }

    func connection(connection: NSURLConnection, didRecieveResponse response: NSURLResponse)  {
        println("Recieved response")
    }

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        self.data = NSMutableData()
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        self.data.appendData(data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        var dataAsString: NSString = NSString(data: self.data, encoding: NSUTF8StringEncoding)
        var err: NSError
        var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        var results: NSArray = json["needs"] as NSArray
        self.dataArray = results

        tableView.reloadData()
        println("success")
    }

//End loading of JSON

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

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count;
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as CustomCell

        var rowData: NSDictionary = dataArray[indexPath.row] as NSDictionary
        var title=rowData["needFirstname"] as String
        var poster=rowData["needCountry"] as String
        var descrip=rowData["needDescription"] as String


        //GDC
        var queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

        dispatch_async(queue, {
            cell.needTitle.text = title
            cell.needPoster.text = poster
            cell.needDescription.text = descrip
            cell.needDescription.numberOfLines = 0
        })

        return cell
    }

}

我的 CustomClass.swift 文件(用于自定义 UITableViewCell)

class CustomCell: UITableViewCell {
    @IBOutlet var needTitle: UILabel!
    @IBOutlet var needPoster: UILabel!
    @IBOutlet var needDescription: UILabel!
}

最佳答案

问题是您在后台线程上设置单元格的 UI 元素,此处:

//GDC
var queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

dispatch_async(queue, {
    cell.needTitle.text = title
    cell.needPoster.text = poster
    cell.needDescription.text = descrip
    cell.needDescription.numberOfLines = 0
})

我不确定您为什么要使用 GCD 来调度那里的后台队列,但您不应该这样做。 所有 UI 元素都必须始终从主线程/队列更新。

简单地摆脱你的 dispatch_async 它应该可以工作:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as CustomCell

    var rowData: NSDictionary = dataArray[indexPath.row] as NSDictionary
    var title=rowData["needFirstname"] as String
    var poster=rowData["needCountry"] as String
    var descrip=rowData["needDescription"] as String

    cell.needTitle.text = title
    cell.needPoster.text = poster
    cell.needDescription.text = descrip
    cell.needDescription.numberOfLines = 0

    return cell
}

关于ios - Swift TableView 重新加载但单元格在单击之前保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25520008/

相关文章:

ios - 如何在 Storyboard/界面生成器中使 UIImageView 成为 UICollectionViewCell 高度的一半

ios - 如何在swift中动态创建单选按钮?

ios - 用户输入不适用于在表格 View 中以编程方式添加的文本字段

iphone - 不同部分的自定义分组 UITable 标题

ios - 以编程方式添加文本替换

ios - 谁应该 swift 将 DisposeBag 保留在 MVVM(+controller) 中

swift - 如何在 vapor 3 中访问查询参数

objective-c - Facebook iOS 登录 - 未调用委托(delegate)方法

iphone - 在 locationManager = nil 和 stopUpdatingLocation 调用后位置仍在监控

ios - 为什么自动调整表格 View 单元格中的 UIImageView 具有内容模式 AspectFit 的原始高度?