Swift 3如何正确编写完成处理程序块

时间:2016-12-20 19:29:41

标签: xcode swift3 completionhandler catransaction performbatchupdates

我是Xcode和编程语言的新手,我需要你的帮助。我正在处理Message应用程序,但我无法使用Completion Handler Block。这是我的代码:

     @IBAction func SendButton(_ sender: AnyObject) {


    if self.textfield.text != "" {


        let mess = CKRecord(recordType: "Message")
        mess["content"] = textfield.text as CKRecordValue?

        let publicdata = CKContainer.default().publicCloudDatabase

        publicdata.save(mess, completionHandler: {(record, error) -> Void in
            if error == nil {


                let indexpath = NSIndexPath(item: self.chat.count, section: 0)


                CATransaction.begin()
                CATransaction.setDisableActions(true)


                self.CollView.performBatchUpdates ({

                    self.chat.insert(mess, at: self.chat.count)
                    self.CollView.insertItems(at: [indexpath as IndexPath])


                }, completion: {(true) -> Void in

                print("Animation completed")
                self.CollView.contentOffset = CGPoint(x: 0, y: 40)

                })

                CATransaction.commit()

            print("SAVED")


            }else{
            print("error")
            }})

    }

    textfield.text = ""
}

我使用CATransaaction来执行BootUpdates,但是performBatchUpdates方法中的Completion Handler Block无法完成。正如你所看到的,它不是写它的正确方式而且我知道它,但是我已经尝试了所有我知道的实现它,但它不会。完成:

 completion: {(true) -> Void in

            print("Animation completed")
            self.CollView.contentOffset = CGPoint(x: 0, y: 40)

            })

请帮帮我。谢谢!!

2 个答案:

答案 0 :(得分:1)

你可以试试这个

collectionView?.performBatchUpdates({
                print("First part")
            }, completion: { (result: Bool) in
                print("Second part")
            })

答案 1 :(得分:0)

 func loadData() {
    chat = [CKRecord]()


let publicData = CKContainer.default().publicCloudDatabase


    let query = CKQuery(recordType: "Message", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    publicData.perform(query, inZoneWith: nil, completionHandler: {(results, error) -> Void in

        if let text = results {
        self.chat = text
            DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { () -> Void in
                self.CollView.reloadData()
            }


        }else{
        print("error")
        }


    })

}