2017-07-06 30 views
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() 
} 
+1

你有一个数据源来处理跟随/跟随? – Starlord

+2

为什么按钮的工作是告诉你用户是否已经关注了?这不是按钮应该做的。 – Alexander

+0

您不应该将视图用作数据存储的方法。什么是决定按钮文字的功能?这将是一个更好的起点。 –

回答

0

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

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

(取决于你是否要使它成为一个可选的,含蓄地展开可选的,或设定的默认值,当然,如果你使用普通的可选你需要解开它的最后一部分)

+0

为什么要让'isFollowing'成为可选项?只要给它一个默认值。 – rmaddy