在视图和视图控制器之间进行委托

时间:2019-05-30 19:53:27

标签: swift delegates

我有一个UIView和一个ViewController。 在UIView中,我有一个UITextField,我需要使用一个委托,以便可以通过点击“完成”按钮来关闭键盘。 问题是我无法在UITextViewDelegate中使用UIView,也无法从UIView访问ViewController中的Textfield。 如何添加代理,以便可以关闭文本字段?

ViewController:

import UIKit


class LoginVC: UIViewController, UITextViewDelegate {
override func loadView() {
    super.loadView()
    self.view = BaseView()
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.tabBarController?.navigationController?.setNavigationBarHidden(true, animated: false)

    navigationItem.title = "LoginVC"
    navigationController?.navigationBar.barTintColor = UIColor.appBlue
    navigationController?.navigationBar.barStyle = .black
    navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.appWhite]
    navigationItem.rightBarButtonItem?.tintColor = UIColor.appWhite

    let btnImage = UIImageView(image: UIImage(named: "Help"))
    btnImage.changeImageColor(color: UIColor.appWhite)

    //TODO: Change the btnImage to color white!
    let helpButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
    helpButton.setImage(btnImage.image, for: .normal)
    helpButton.addTarget(self, action: #selector(showHelpPopup), for: .touchUpInside)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: helpButton)

}

@objc func showHelpPopup(){

}
}

查看:

import UIKit

public final class BaseView: UIView, UITextFieldDelegate {
public override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(masterStackView)

    self.backgroundColor = UIColor.white
    NSLayoutConstraint.activate([
        masterStackView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        masterStackView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        masterStackView.leadingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.leadingAnchor, multiplier: 0.2),
        masterStackView.trailingAnchor.constraint(lessThanOrEqualToSystemSpacingAfter: self.trailingAnchor, multiplier: -0.2),
        masterStackView.heightAnchor.constraint(equalToConstant: 100),
    ])
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public let addCommentTextField: UITextField = {
    let text = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 30))

    text.placeholder = "Comment"
    text.font = UIFont.systemFont(ofSize: 14, weight: .bold)
    text.borderStyle = UITextField.BorderStyle.roundedRect
    text.autocorrectionType = UITextAutocorrectionType.no
    text.keyboardType = UIKeyboardType.default
    text.returnKeyType = UIReturnKeyType.done
    text.clearButtonMode = .always
    text.contentHorizontalAlignment = .left

    return text
}()

1 个答案:

答案 0 :(得分:1)

不需要你做

self.view.endEditing(true)

let vi = BaseView()
vi.addCommentTextField.delegate = self
self.view = vi