2017-07-06 72 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