为不同的视图使用共享类

时间:2018-04-08 23:16:06

标签: ios swift

我有一个入职用户流程:

Name -> Age -> Gender

每个屏幕共享相同的结构:

Question (top)
Input (middle)
Continue (bottom)

我有一个类OnboardingHelper.swift,它创建一个类来设置问题框并继续按钮:

class UserOnboardingHelper{
   var text: String
   var questionbox: UIView
   var viewController: UIViewController
   var continueButton: UIButton

   init(text: String, questionbox: UIView, viewController: UIViewController, continueButton: UIButton){
      self.text = text
      self.questionbox = questionbox
      self.viewController = viewController
      self.continueButton = continueButton
   }
   func setQuestionBox(){
       //sets question box
   }
   func setContinueButton(){
       //sets continue button
       enableContinueButton()
       addContinueButtonPath()
   }
   func enableContinueButton(){
       //enables continue button
   }
   func disableContinueButton(){
       //disables continue button
   }
   func addContinueButtonPath(){
       //sets path of continue button based on which view
   }
}

在每个入职的ViewControllers中,我在ViewDidLoad()中设置类:

class NamePageViewController: UIViewController, UITextFieldDelagate {
    @IBOutlet weak var questionbox: UIView!
    @IBOutlet weak var continueButton: UIButton!
    @IBOutlet weak var inputLabel: UITextField!

    override func viewDidLoad() {
       super.viewDidLoad()
       let namePageSettings = UserOnboardingHelper(text: "What is your name", questionbox: questionbox, viewController: self, continueButton: continueButton)
       namePageSettings.setQuestionBox()
       namePageSettings.setContinueButton()
       inputLabel.delegate = self
       if nameIsFilled {
          namePageSettings.enableContinueButton()
       } else{
          namePageSettings.disableContinueButton()
       }
    }
}

问题是在ViewController中我的textFieldDidEndEditing()函数需要从viewDidLoad()中调用namePageSettings类

    func textFieldDidEndEditing(_ textField: UITextField){
        if (textField.text?.empty)!{
            //I want to call disableContinueButton() from UserOnboardingHelper
        } else {
            //I want to enable enableContinueButton() from UserOnboardingHelper
        }
    }

试图了解是否:

  1. 整体方法是正确的,如果没有,最好的方法是什么
  2. 如果上述方法是正确的方向,应该如何调用disableContinueButton()和enableContinueButton()?
  3. 提前致谢!对不起,如果方法真的很愚蠢 - 我仍然试图绕着课程。

1 个答案:

答案 0 :(得分:0)

您可以让视图控制器对入门助手有一个弱引用,因此您仍然可以调用辅助方法而不创建保留周期。

NamePageViewController中,添加一个属性:

weak var userOnboardingHelper: UserOnboardingHelper?

然后,在UserOnboardingHelper的初始值设定项中,添加:

self.viewController.userOnboardingHelper = self

您现在可以在视图控制器中调用onboarding helper的方法:

userOnboardingHelper.disableContinueButton()
userOnboardingHelper.enableContinueButton()