gpt4 book ai didi

ios - 将数据传递给自定义 View 然后执行函数是一种好方法吗?

转载 作者:行者123 更新时间:2023-11-28 10:31:50 25 4
gpt4 key购买 nike

我创建了一个自定义输入附件 View ,它是提交按钮。但是,我需要将数据传递给自定义 View ,然后执行进一步的功能。这是一个很好的方法吗?

class SignUpViewController: UIViewController {

@IBOutlet weak var phoneTF: SignLogTextField!
@IBOutlet weak var EmailTF: SignLogTextField!
@IBOutlet weak var PasswordTF: SignLogTextField!
@IBOutlet weak var FBBtn: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
textFieldPreparation()
}

func textFieldPreparation(){
EmailTF.inputAccessoryView = Bundle.main.loadNibNamed("SignSubmitBTN", owner: self, options: nil)?.first as! SignSubmitBTN

phoneTF.inputAccessoryView = Bundle.main.loadNibNamed("SignSubmitBTN", owner: self, options: nil)?.first as! SignSubmitBTN

PasswordTF.inputAccessoryView = Bundle.main.loadNibNamed("SignSubmitBTN", owner: self, options: nil)?.first as! SignSubmitBTN
}
}

enter image description here

我不确定如何将数据传递到自定义 View ,或者我应该在 Outlet Action 中执行 sign up 吗?

这是我的自定义 View

import UIKit

class SignSubmitBTN: UIView {
@IBAction func submitAction(_ sender: Any) {
}

@IBOutlet weak var subBTN: UIButton!

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

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

func setup(){}
}

如果我必须将数据传递给自定义 View ,我应该使用协议(protocol)吗?如果我应该使用协议(protocol)怎么用呢?

最佳答案

好的...

我认为您是从错误的方向来处理这个问题的。按钮的职责应该是告诉您用户点击了它,仅此而已。该按钮不应处理登录。

但是……你已经完成了这里的 90%。只需再添加几位。

您可以更新提交按钮以包含委托(delegate)并在按钮操作中使用委托(delegate)...

import UIKit

// protocol
protocol SignInButtonDelegate: class {
func signIn()
}

class SignSubmitBTN: UIView {
// property for delegate
weak var delegate: SignInButtonDelegate?

@IBAction func submitAction(_ sender: Any) {
// this tells the delegate to sign in
// it doesn't need to know how that happens
delegate?.signIn()
}

@IBOutlet weak var subBTN: UIButton!

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

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

func setup() {}
}

然后在您的 View Controller 中您遵守委托(delegate)协议(protocol)...

extension SignUpViewController: SignInButtonDelegate {
func signIn() {
// here you already have access to all the data you need to sign in.
// you are in the view controller here so just get the text from the username, password, etc...
}
}

然后将 View Controller 设置为委托(delegate)...

func textFieldPreparation() {
let signInButton = Bundle.main.loadNibNamed("SignSubmitBTN", owner: self, options: nil)?.first as! SignSubmitBTN
signInButton.delegate = self

// these are properties... they should begin with a lowercase letter
emailTF.inputAccessoryView = signInButton
phoneTF.inputAccessoryView = signInButton
passwordTF.inputAccessoryView = signInButton
}

关于ios - 将数据传递给自定义 View 然后执行函数是一种好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55664618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com