Home > Mobile >  How to reuse view for similar but slightly different views in iOS?
How to reuse view for similar but slightly different views in iOS?

Time:07-29

I'm making login flow right now.
There is two view controllers for email input and password input.
After validating email account, password input view controller pops up.

The email VC and password VC is very similar but slightly different.
just like "Enthr email" & "Enter password" (UILabel text)

I think that making custom view and reusing it is efficient.
But the two view controllers need different value(email, password string).
How can I pass different value to same custom view?

Or how can I reuse view for similar views programmatically?

CodePudding user response:

You can create Views and reuse them by using different parameters when calling them. Something like this :

struct ContentView: View {
    var body: some View {
        ZStack {
            CustomView("text1")
            CustomView("text2")
        }
    }
}

// Custom reusable view
struct CustomView: View {
    var value:String

    var body: some View{
         Text(value)
    }
}

CodePudding user response:

For UIKit You can create custom textField component that takes inputType and specific customization related to that.

 enum InputType {
        case email
        case password
    }

class InputViewController: UIViewController { 
    let customTextField: CustomTextField!
    var inputType: InputType!
    
    convenience init(inputType: InputType) {
        self.init()
        self.inputType = inputType
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        customTextField = CustomTextField(inputType: self.inputType)
    }
}
  • Related