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
您不應該將視圖用作數據存儲的方法。什麼是決定按鈕文字的功能?這將是一個更好的起點。 –