我想将用户名设置为标签,因为我的块(“findObjectsInBackgroundWithBlock”)需要时间来完成, label.text 设置 nil 。
如何在完成块后设置标签文本?
class test {
var userName: String? // variable to access user name returned by block
private func loadData() {
getCurrentUser()
lblUserName.text = userName
}
}
这是我从Parse获取用户数据的块。
private func getCurrentUser() {
if PFUser.currentUser() != nil {
currentUser = PFUser.currentUser()?.username
let query = PFQuery(className: "_User")
query.whereKey("username", equalTo: currentUser!)
query.findObjectsInBackgroundWithBlock { (currentUsers, error) -> Void in
if error == nil {
for user in currentUsers! {
userName = user["name"] as? String
}
}
}
}
}
答案 0 :(得分:1)
您可以像这样使用属性观察者:
var userName: String? {
didset {
if let name = username {
lblUserName.text = name
}
}
}
答案 1 :(得分:1)
您可以向getCurrentUser函数添加一个完成处理函数参数,并在您重新获取数据时调用该处理函数:
private func getCurrentUser(completion: (result: String) -> Void) {
if PFUser.currentUser() != nil {
currentUser = PFUser.currentUser()?.username
let query = PFQuery(className: "_User")
query.whereKey("username", equalTo: currentUser!)
query.findObjectsInBackgroundWithBlock { (currentUsers, error) -> Void in
if error == nil {
for user in currentUsers! {
completion(user["name"] as? String)
}
}
}
}
}
然后传递complition函数:
getCurrentUser() { (result: String) in
self.lblUserName.text = result
}
我无法证明它是完全正常工作的代码,因为我现在没有XCode来测试它。但你应该明白这个想法。
答案 2 :(得分:0)
您可以使用在getCurrentUser函数中定义的回调
private func loadData() {
getCurrentUser({
self.lblUserName.text = userName
})
}
private func getCurrentUser(callback: () -> ()){
// Your code
callback()
}
答案 3 :(得分:0)
const
是异步调用。一旦从服务器收到响应,提供给它的完成块就会在一个单独的线程中执行。
如果在行query.findObjectsInBackgroundWithBlock
中放置断点并逐步进入流程,您将能够清楚地了解流程。
您可以通过不同的方式实现结果,
- 您可以为
醇>getCurrentUser()
设置属性观察者并将更改设置为 你的userName
lblUserName
- 您可以在完成时更新
醇>var userName: String? { willSet(newUserName) { if let username = newUserName { lblUserName.text = username } } }
的值 块