0
@IBAction func followUser(_ sender: Any) {
if followBtn.titleLabel?.text == "Follow"{
print("will follow")
} else if followBtn.titleLabel?.text == "Following"{
}
}
有没有更好的方法来做到这一点?我有一个负载运行的函数,然后检查用户是否被关注并更改按钮的文本。当然,如果按钮显示“跟随”,它将具有与“跟随”按钮不同的功能。这是我能做到的唯一方法吗?感觉不对。区分按钮的更好方法Swift?
func checkFollowing(){
let url = URL(string: "xxx")
//request to this file
var request = URLRequest(url: url!)
//method to pass data
request.httpMethod = "POST"
//body to be appended to url
let body = "id=\(user?["id"] as! String)&follower_id=\(imageID)"
request.httpBody = body.data(using: String.Encoding.utf8) //multi language support
//launching
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
if error == nil{
//communicate back to UI
DispatchQueue.main.async(execute: {
do{
//get json result
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?
NSDictionary
//assign json to a new var parseJSON in guard secured way
guard let parseJSON = json else{
print("error while parsing")
return
}
if parseJSON["status"] as! String == "1"{
self.followBtn.setTitle("Following", for: .normal)
self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
} else if parseJSON["status"] as! String == "0"{
self.followBtn.setTitle("Follow", for: .normal)
}
} catch{
print("Caught an error: \(error)")
}
})
//if unable to proceed with request
} else{
print("error: \(error)")
}
//launch prepared session
}).resume()
}
你有一个数据源来处理跟随/跟随? – Starlord
为什么按钮的工作是告诉你用户是否已经关注了?这不是按钮应该做的。 – Alexander
您不应该将视图用作数据存储的方法。什么是决定按钮文字的功能?这将是一个更好的起点。 –