在函数中快速添加子视图

时间:2018-07-12 11:43:07

标签: swift subview

我试图在按下按钮时显示加载子视图。我不确定为什么,但是子视图仅在显示警报视图时出现。我希望功能开始后立即显示加载屏幕。

是什么原因造成的,我该如何纠正?

 @IBAction func registerManual(_ sender: Any) {

        // Check the validity of the inputs
        let isValid = manualRegistration().validate(firstName: "\(String(describing: firstName.text!))", lastName: "\(String(describing: lastName.text!))", email: "\(String(describing: email.text!))", password: "\(String(describing: password.text!))", dob: dobSelected)

        if(isValid == "success"){
            let loadingScreen = xibLoad().loadingScreen()
            loadingScreen.frame.size.height = view.frame.height
            loadingScreen.tag = 100
            view.addSubview(loadingScreen)

            // Submit to backend.
            let params = "firstname=\(escpae().url(string: firstName.text!))&lastname=\(escpae().url(string:lastName.text!))&email=\(escpae().url(string:email.text!))&dob=\(escpae().url(string: selectedDateText.text!))&password=\(escpae().url(string:password.text!))&currency=\(currency)&language=\(language)&region=\(region)"

            let resultArray = serverCall().post(endPoint: "registermanual.php?", params: "\(params)", fromViewController: self)    

            if(resultArray.count > 0 && resultArray[0]["error"] == nil){
                self.defaults.set("\(resultArray[0]["token"]!)", forKey: "token")
                DispatchQueue.main.async {
                self.performSegue(withIdentifier:"goLoading", sender: self)
                }
            }
            if(resultArray.count > 0 && resultArray[0]["error"] != nil){
                alert().show(title: "ERROR", message: "\(resultArray[0]["error"]!)", button: "OK", viewc: self)
            }
        }else{
            alert().show(title: "Oops!", message: "\(isValid)", button: "OK", viewc: self)
        }
    }

加载屏幕:

class loadingScreen: UIView {

    @IBOutlet weak var gifView: UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        //custom logic goes here
         gifView.loadGif(name: "loading")
    }

}

1 个答案:

答案 0 :(得分:0)

您可以尝试执行此操作,即使您从if语句中添加子视图,也要花费几毫秒的时间(取决于验证时间),但这会阻止任何用户事件

@IBAction func registerManual(_ sender: Any) {


   loadingScreen.frame.size.height = view.frame.height
   loadingScreen.tag = 100
   view.addSubview(loadingScreen)
   // view.layoutSubviews() don't call it directly

    // Check the validity of the inputs
    let isValid = manualRegistration().validate(firstName: "\(String(describing: firstName.text!))", lastName: "\(String(describing: lastName.text!))", email: "\(String(describing: email.text!))", password: "\(String(describing: password.text!))", dob: dobSelected)
    if(isValid == "success"){