gpt4 book ai didi

swift - 区分 Swift 按钮的更好方法?

转载 作者:行者123 更新时间:2023-11-30 12:19:35 25 4
gpt4 key购买 nike

@IBAction func followUser(_ sender: Any) {
if followBtn.titleLabel?.text == "Follow"{
print("will follow")
} else if followBtn.titleLabel?.text == "Following"{
}
}

有更好的方法吗?我有一个在加载时运行的函数,然后检查用户是否被关注并更改按钮的文本。当然,如果按钮说“关注”,它将具有与说“关注”的按钮不同的功能。这是我能做到的唯一方法吗?感觉不对。

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()
}

最佳答案

通过 Controller 上的变量跟踪其状态将是更好的方法。

var isFollowing: Bool!

// -------------------------------

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)
self.isFollowing = true
} else if parseJSON["status"] as! String == "0"{
self.followBtn.setTitle("Follow", for: .normal)
self.isFollowing = false
}

// -------------------------------

@IBAction func followUser(_ sender: Any) {
if self.isFollowing {
// whatever happens when you're already following
} else {
print("will follow")
}
}

(由您决定是否要将其设为可选、隐式解包可选,或设置默认值,但当然,如果您使用常规可选,则需要在最后一部分解包它)

关于swift - 区分 Swift 按钮的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com