簡體   English   中英

如何使用Swift在視圖控制器中隱藏/顯示按鈕?

[英]How to hide/show button in view controller using Swift?

如何在視圖控制器中隱藏和顯示按鈕,例如UserRole =“ Admin”顯示按鈕,而UserRole =“ User”隱藏按鈕。 我已經在下面的AppDelegate類中編寫了代碼,以及如何在視圖控制器類隱藏和顯示button中編寫方法方法名稱為:isItAdminOrNot

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    //var email = (String)()

    if (error == nil) {
        let givenName = user.profile.name
        let email = user.profile.email

        let param = ["UserName": givenName!, "Email": email!] as Dictionary<String, String>

        let request = NSMutableURLRequest(url: NSURL(string: "http://beta.json-generator.com/api/json/get/EJoC6gB_z")! as URL)

        let session = URLSession.shared
        request.httpMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] {

                    print("Response: \(json)")

                    let USerresponse = json["UserRole"] as! String
                    print(USerresponse)
                    DispatchQueue.main.async {
                        // now update UI on main thread

                        DispatchQueue.main.async {
                            // now update UI on main thread
                            self.userRoleValue(userRole: USerresponse)
                        }
                    }
                } else {
                    let jsonStr = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")


                    if let data1 = jsonStr?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {

                        do {
                            if let dictionary = try JSONSerialization.jsonObject(with: data1, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] {

                                let arrayVlaues = dictionary as Array
                                print(arrayVlaues[0])
                                let userRole = arrayVlaues[0].value(forKey: "UserRole") as! String

                                DispatchQueue.main.async {
                                    // now update UI on main thread
                                    self.userRoleValue(userRole: userRole)
                                }


                            }
                        }
                    }

                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()

        // ...
    } else {
        print("\(error.localizedDescription)")
    }
}

func userRoleValue(userRole: String) {
    if(userRole == "User") {
        self.loadParticlularController(value: 1)
    } else if(userRole == "Admin") {
        self.loadParticlularController(value: 2)
    } else if(userRole == "NewUser") {
        self.loadParticlularController(value: 0)
    }
}

func loadParticlularController(value: Int) {
    print(value)

    let myStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var pageNav: UINavigationController;
    let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    // New User
    if (value == 0) {
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "ApprovalUser") as! ApprovalUser

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    } else if(value == 1) { // Existing User
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

        homePage.isItAdminOrNot(val: false)

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    } else if(value == 2) { // Existing User with Admin
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        homePage.isItAdminOrNot(val: true)

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    }
}

試試吧,

如果按鈕的名稱是homePageButton,

homePageButton.isHidden = true
homePageButton.isHidden = false

在HomeViewController的viewDidLoadviewWillAppear方法中顯示/隱藏按鈕。

在你的下

homePage.isItAdminOrNot(val: false)

添加:

homePage.button.isHidden = true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM