简体   繁体   English

封闭中的自我实例

[英]Self instance inside a closure

I'm having a problem trying to animate and change some properties of ui elements inside a closure. 我在尝试动画和更改闭包内ui元素的某些属性时遇到问题。 When I tried to animate some views through a function, It execute the function but the animation fail to complete, nevertheless when I execute the function outside the closure, it works fine. 当我尝试通过函数为某些视图设置动画时,它执行该函数,但动画无法完成,但是当我在闭包外部执行该函数时,它仍然可以正常工作。 This is my code, my problem is in the delegate extension at the bottom of AuthController , function called facebookAuth . 这是我的代码,我的问题出在AuthController底部的委托扩展中,该函数称为facebookAuth I've been struggling almost for a day and I can not find the error. 我几乎已经挣扎了一天,但找不到错误。

I put some print statements inside the animation and function to track down purpose, these are the ones executing: 我在动画和函数中放置了一些打印语句以跟踪目的,这些是执行的语句:

Login successful (this one is in the delegate function 登录成功(这是在委托功能中)

slide (this one is in the slide function) 幻灯片(此功能在幻灯片功能中)

not complete (this one is in the animation closure) 不完整(这是在动画闭包中)

AuthController AuthController

import UIKit
import AVFoundation
import FBSDKLoginKit
import FBSDKCoreKit
import Firebase

protocol AuthControllerDelegate {
    func login(withUser user: User)
    func facebookAuth()
    func signUp(withUser user: User)
    func facebookRegister(withEmail email: String, cellphone: String)
}

class AuthController: UIViewController {

    enum AuthView {
        case registerView
        case loginView
        case fbRegisterSecondStepCenter
    }

    private var player: AVPlayer!
    private var playerLayer: AVPlayerLayer!
    private var registerViewCenterConstraint: NSLayoutConstraint?
    private var loginViewCenterConstraint: NSLayoutConstraint?
    private var fbRegisterSecondStepCenterConstraint: NSLayoutConstraint?
    private var currentView: AuthView = .loginView
    private var facebookUserStore: User?

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    private let purpleBackground: UIView = {
        let pb = UIView()
        pb.backgroundColor = .darkBackground
        pb.alpha = 0.5
        return pb
    }()

    //MARK: AuthViews

    private lazy var loginView: LoginView = {
        let view = LoginView()
        view.delegate = self
        return view
    }()

    private lazy var registerView: RegisterView = {
        let view = RegisterView()
//        view.delegate = self
        view.alpha = 0
        return view
    }()

    private lazy var fbRegisterSecondStep: FBRegisterSecondStep = {
        let view = FBRegisterSecondStep()
        view.alpha = 0
        view.delegate = self
        return view
    }()

    private lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        let attributedString = NSMutableAttributedString(string: "Not registered? Sign up.", attributes: [.foregroundColor: UIColor.lightText, .font: UIFont.init(name: Fonts.lightFont.rawValue, size: 16)!])
        btn.setAttributedTitle(attributedString, for: .normal)
        btn.contentHorizontalAlignment = .center
        btn.addTarget(self, action: #selector(handleChangeView), for: .touchUpInside)
        return btn
    }()

    let alertController: AlertController = {
        let ac = AlertController()
        return ac
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        print(UserDefaults.Account.bool(forKey: .isUserLoggedIn))
        setVideoBackground()
        setupViews()
        alertController.transitioningDelegate = alertController
        alertController.modalPresentationStyle = .custom
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.isNavigationBarHidden = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.isNavigationBarHidden = false
    }

    private func setupViews() {
        view.addSubview(purpleBackground)
        view.addSubview(loginView)
        view.addSubview(registerView)
        view.addSubview(fbRegisterSecondStep)
        view.addSubview(bottomBtn)

        _ = purpleBackground.anchor(top: view.topAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, left: view.leftAnchor)

        loginViewCenterConstraint = loginView.centerInView().first
        _ = loginView.anchorWithMultiplier(top: nil, bottom: nil, right: nil, left: nil, height: view.heightAnchor, width: view.widthAnchor, topConstant: 0, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0.8, heightMultiplier: 0.6)

        registerViewCenterConstraint = registerView.centerInView().first
        registerViewCenterConstraint?.constant = 1000
        _ = registerView.anchorWithMultiplier(top: nil, bottom: nil, right: nil, left: nil, height: view.heightAnchor, width: view.widthAnchor, topConstant: 0, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0.8, heightMultiplier: 0.8)

        fbRegisterSecondStepCenterConstraint = fbRegisterSecondStep.centerInView().first
        fbRegisterSecondStepCenterConstraint?.constant = 1000
        _ = fbRegisterSecondStep.anchorWithMultiplier(top: nil, bottom: nil, right: nil, left: nil, height: view.heightAnchor, width: view.widthAnchor, topConstant: 0, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0.8, heightMultiplier: 0.5)

        _ = bottomBtn.anchor(top: nil, bottom: view.bottomAnchor, right: view.rightAnchor, left: view.leftAnchor, topConstant: 0, bottomConstant: 20, rightConstant: 0, leftConstant: 0, widthConstant: 0, heightConstant: 0)
    }

    private func setVideoBackground() {
        let videoPath = Bundle.main.url(forResource: "trim720", withExtension: "mp4")
        player = AVPlayer(url: videoPath!)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = .resizeAspectFill
        playerLayer.frame = view.frame
        player.actionAtItemEnd = .none
        player.play()

        view.layer.insertSublayer(playerLayer, at: 0)

        NotificationCenter.default.addObserver(self, selector: #selector(handleStop), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
    }

    private func slide(toView view: AuthView, completion: @escaping (Bool) -> Void = { _ in }) {
        guard let registerCenterConstraint = registerViewCenterConstraint, let loginCenterConstraint = loginViewCenterConstraint, let fbRegisterSecondConstraint = fbRegisterSecondStepCenterConstraint else {
            fatalError("Error unwrapping auth views constraints.")
        }
        switch view {
        case .loginView:
            loginCenterConstraint.constant = 0
            registerCenterConstraint.constant = 1000
            fbRegisterSecondConstraint.constant = 1000
            currentView = .loginView
        case .registerView:
            loginCenterConstraint.constant = 1000
            registerCenterConstraint.constant = 0
            fbRegisterSecondConstraint.constant = 1000
            currentView = .registerView
        case .fbRegisterSecondStepCenter:
            loginCenterConstraint.constant = 1000
            registerCenterConstraint.constant = 1000
            fbRegisterSecondConstraint.constant = 0
            currentView = .fbRegisterSecondStepCenter
            print("slideeeeeeeeeeee")
        }
        let isRegisterVisible = registerCenterConstraint.constant == 0
        let isLoginVisible = loginCenterConstraint.constant == 0
        let isFbRegisterVisible = fbRegisterSecondConstraint.constant == 0

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.registerView.alpha = isRegisterVisible ? 1 : 0
            self.loginView.alpha = isLoginVisible ? 1 : 0
            self.fbRegisterSecondStep.alpha = isFbRegisterVisible ? 1 : 0
            self.view.layoutIfNeeded()
            print("slide")
        }) { (state) in
            if state {
                print("completed")
            } else {
                print("not completed")
            }
            completion(state)
        }
    }

    fileprivate func pushHome() {
        navigationController?.isNavigationBarHidden = false
        navigationController?.setViewControllers([HomeController()], animated: true)
    }

    // MARK: Handlers

    @objc private func handleStop() {
        player.seek(to: kCMTimeZero)
    }

    @objc private func handleChangeView() {

        let isLoginVisible = currentView == .loginView
        let view: AuthView = isLoginVisible ? .registerView : .loginView
        slide(toView: view) { (completed) in
            let attributedString = self.bottomBtn.attributedTitle(for: .normal) as! NSMutableAttributedString
            let newTitle = isLoginVisible ? "Already an user? Sign In" : "Not registered? Sign up."
            attributedString.mutableString.setString(newTitle)
        }
    }
}

extension AuthController: Loginable, Registable, AuthControllerDelegate {

    func login(withUser user: User) {
        signIn(withUser: user) { (_) in
            self.pushHome()
        }
    }

    func facebookAuth(){
        let loginManager = FBSDKLoginManager()
        loginManager.logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, err) in
            if err == nil, !(result?.isCancelled)!, let token = result?.token.tokenString {
                print("Login successful")
                self.loginView.isHidden = true
                self.bottomBtn.isHidden = true
                self.slide(toView: .registerView)
            }
        }
    }

    func facebookRegister(withEmail email: String, cellphone: String) {
        guard let user = facebookUserStore else {
            fatalError("Error linking accounts")
        }
        register(withUser: user) { (completed) in
            if completed {
                self.linkAccount(withEmail: email, cellphone: cellphone, completion: { (completion) in
                    if completion {
                        self.pushHome()
                    }
                })
            }
        }
    }

    func signUp(withUser user: User) {
        register(withUser: user) { (_) in
            print("registrado")
            UserDefaults.Account.set(true, forKey: .isUserLoggedIn)
            self.pushHome()
        }
    }
}

The function execute through a delegate inside this view when the fbButton is clicked. 单击fbButton时,该函数通过此视图内的委托执行。

LoginView 登录查看

//
//  LoginView.swift
//  TaxiApp
//
//  Created by Leonardo Dominguez on 10/2/17.
//  Copyright © 2017 Leonardo Dominguez. All rights reserved.
//

import UIKit

class LoginView: BaseView {

    var delegate: AuthControllerDelegate?

    private let emailField: TAField = {
        let pf = TAField(placeHolder: "E-mail", keyboardType: .emailAddress)
        return pf
    }()

    private let passwordField: TAField = {
        let pf = TAField(placeHolder: "Password")
        pf.isSecureTextEntry = true
        return pf
    }()

    private lazy var loginBtn: TAButton = {
        let btn = TAButton(title: "Login")
        btn.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
        return btn
    }()

    private let facebookBtn: TAButton = {
        let btn = TAButton()
        btn.backgroundColor = UIColor(hexString: "#3b5998")
        btn.setAttributedTitle(NSAttributedString(string: "Login with Facebook", attributes: [.foregroundColor: UIColor.lightText, .font: UIFont.init(name: Fonts.mediumFont.rawValue, size: 20)!]), for: .normal)
        return btn
    }()

    private let forgotPassword: UIButton = {
        let btn = UIButton()
        btn.setAttributedTitle(NSAttributedString(string: "Forgot password", attributes: [.foregroundColor: UIColor.placeholderText, .font: UIFont.init(name: Fonts.mediumFont.rawValue, size: 16)!]), for: .normal)
        btn.contentHorizontalAlignment = .right
        return btn
    }()

    private let orView: UIView = {
        let container = UIView()
        let lbl = UILabel()
        lbl.text = "or"
        lbl.textColor = .lightText
        lbl.font = UIFont(name: Fonts.mediumFont.rawValue, size: 20)
        let leftLine = UIView()
        let rightLine = UIView()
        leftLine.backgroundColor = .lightLine
        rightLine.backgroundColor = .lightLine
        container.addSubview(rightLine)
        container.addSubview(lbl)
        container.addSubview(leftLine)
        rightLine.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
        _ = rightLine.anchor(top: nil, bottom: nil, right: container.rightAnchor, left: lbl.rightAnchor, topConstant: 0, bottomConstant: 0, rightConstant: 70, leftConstant: 3, widthConstant: 0, heightConstant: 1.0)
        _ = lbl.centerInView()
        leftLine.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
        _ = leftLine.anchor(top: nil, bottom: nil, right: lbl.leftAnchor, left: container.leftAnchor, topConstant: 0, bottomConstant: 0, rightConstant: 3, leftConstant: 70, widthConstant: 0, heightConstant: 1.0)
        return container
    }()

    override func setupViews() {
        setupBtns()

        addSubview(emailField)
        addSubview(passwordField)
        addSubview(forgotPassword)
        addSubview(loginBtn)
        addSubview(orView)
        addSubview(facebookBtn)

        _ = emailField.anchor(top: topAnchor, bottom: nil, right: rightAnchor, left: leftAnchor, topConstant: 20, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthConstant: 0, heightConstant: Theme.fieldHeight)

        _ = passwordField.anchorWithMultiplier(top: emailField.bottomAnchor, bottom: nil, right: emailField.rightAnchor, left: emailField.leftAnchor, height: emailField.heightAnchor, width: nil, topConstant: Theme.topPadding, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0, heightMultiplier: 1)

        _ = forgotPassword.anchor(top: passwordField.bottomAnchor, bottom: nil, right: emailField.rightAnchor, left: emailField.leftAnchor, topConstant: 5, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthConstant: 0, heightConstant: 0)

        _ = loginBtn.anchorWithMultiplier(top: passwordField.bottomAnchor, bottom: nil, right: emailField.rightAnchor, left: emailField.leftAnchor, height: emailField.heightAnchor, width: nil, topConstant: Theme.topPadding, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0, heightMultiplier: 1)

        _ = orView.anchor(top: loginBtn.bottomAnchor, bottom: nil, right: rightAnchor, left: leftAnchor, topConstant: Theme.topPadding / 2, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthConstant: 0, heightConstant: 10)

        _ = facebookBtn.anchorWithMultiplier(top: orView.bottomAnchor, bottom: nil, right: emailField.rightAnchor, left: emailField.leftAnchor, height: emailField.heightAnchor, width: nil, topConstant: Theme.topPadding / 2, bottomConstant: 0, rightConstant: 0, leftConstant: 0, widthMultiplier: 0, heightMultiplier: 1)

    }

    func setupBtns() {
        facebookBtn.addTarget(self, action: #selector(handleFacebookLogin), for: .touchUpInside)
    }

    @objc func handleFacebookLogin() {
        delegate?.facebookAuth()
    }

    @objc func handleLogin() {
        if let email = emailField.text, let password = passwordField.text {
            let user = User(email: email, password: password)
            delegate?.login(withUser: user)
        }
    }

}

UPDATE 更新

So after a lot of patinete trying the whole app, I just notice that the error belong to a RouterController that is a UINavigationController subclass where AuthController is embed. 因此,在尝试了整个应用程序的大量程序之后,我只是注意到该错误属于RouterControllerAuthController是嵌入AuthController的UINavigationController子类。 When I change the windows rootviewcontroller to avoid RouterController and go directly to AuthController , everything Start to work.. Now my doubt is, why this is happening? 当我更改Windows rootviewcontroller以避免RouterController并直接转到AuthController ,一切开始正常工作。现在我的疑问是,为什么会这样? I was trying to figure out, so I can fixed or in future cases but I don't know why, here is my code: 我试图弄清楚,所以我可以修复或在以后的情况下使用,但我不知道为什么,这是我的代码:

RouterController 路由器控制器

import UIKit

class RouterController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
//        perform(#selector(redirect), with: nil, afterDelay: 0)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        redirect()
    }

    @objc func redirect() {
        if UserDefaults.Account.bool(forKey: .isUserLoggedIn) {
            viewControllers = [HomeController()]
        } else {
            setViewControllers([AuthController()], animated: false)
        }
    }
}

Try executing everything in the closure on the main thread like so: 尝试像这样在主线程的闭包中执行所有操作:

func facebookAuth(){
    let loginManager = FBSDKLoginManager()
    loginManager.logIn(withReadPermissions: ["email", "public_profile"], from: self) {[weak self] (result, err) in
        if err == nil, !(result?.isCancelled)!, let token = result?.token.tokenString {
            print("Login successful")
            DispatchQueue.main.async {
                self?.loginView.isHidden = true
                self?.bottomBtn.isHidden = true
                self?.slide(toView: .registerView)
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM