我是swift并且不使用故事板创建应用程序的新手。我创建了logincontroller并附加了loginview。当有人完成电子邮件和密码文本字段并从键盘点击返回键时,我想检测事件,以便我可以处理用户登录请求。
这是我的代码。
import UIKit
class LoginController: UIViewController {
var loginView: LoginView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
let mainView = LoginView(frame: self.view.frame)
self.loginView = mainView
self.view.addSubview(loginView)
}
和LoginView.swift的代码
import UIKit
class LoginView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
backgroundColor = .white
let stackView = createStackView(views: [emailTextField,passwordTextField])
addSubview(stackView)
//autolayout constraints here
}
let emailTextField: UITextField = {
let tf = UITextField(placeHolder: "Email")
return tf
}()
let passwordTextField: UITextField = {
let tf = UITextField(placeHolder: "Password")
tf.isSecureTextEntry = true
tf.returnKeyType = UIReturnKeyType.send
return tf
}()
答案 0 :(得分:1)
只需将其添加到setup
方法
func setup() {
backgroundColor = .white
let stackView = createStackView(views: [emailTextField,passwordTextField])
addSubview(stackView)
emailTextField.delegate = self // This
passwordTextField.delegate = self // And this
}
然后在LoginView
课程
extension LoginView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == passwordTextField {
passwordTextField.resignFirstResponder()
doWhatYouWantTo() // eg. do your login
} else {
passwordTextField.becomeFirstResponder()
}
return false
}
}
扩展Anwer -
class LoginController: UIViewController {
var loginView: LoginView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
let mainView = LoginView(frame: self.view.frame)
self.loginView = mainView
self.loginView.delegate = self
self.view.addSubview(loginView)
}
}
extension LoginController: LoginViewDelegate{
func userWantsToLoginWith(userName: String?, password: String?) {
// Now you have both userName and password here
}
}
protocol LoginViewDelegate: class {
func userWantsToLoginWith(userName: String?, password: String?)
}
class LoginView: UIView {
var delegate: LoginViewDelegate?
let emailTextField: UITextField = {
let tf = UITextField(placeHolder: "Email")
return tf
}()
let passwordTextField: UITextField = {
let tf = UITextField(placeHolder: "Password")
tf.isSecureTextEntry = true
tf.returnKeyType = UIReturnKeyType.send
return tf
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
backgroundColor = .white
let stackView = createStackView(views: [emailTextField, passwordTextField])
addSubview(stackView)
//autolayout constraints here
}
}
extension LoginView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == passwordTextField {
passwordTextField.resignFirstResponder()
delegate?.userWantsToLoginWith(userName: emailTextField.text, password: passwordTextField.text)
} else {
passwordTextField.becomeFirstResponder()
}
return false
}
}