首页 > 解决方案 > 如何在leftBarButtonItems中将文本字段添加为自定义视图,此处文本字段需要能够输入

问题描述

如何添加一个新视图,该视图中包含文本字段和按钮,以及如何在 leftbarbuttonitmes 中添加此视图,并且文本字段需要能够输入。

现在我已成功将此视图添加到 leftbarbuttonitems 但我的文本字段无法输入。如果我们添加leftbarbuttonitems,有什么方法可以输入。

标签: swift3swift4

解决方案


在这里:只需将以下代码粘贴到您的 viewDidLoad 方法中。

        let viewLeftButton: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 160.0, height: 32.0))

        let textField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 100.0, height: viewLeftButton.frame.size.height))
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 14.0)
        textField.placeholder = "Type here..."

        let button: UIButton = UIButton(frame: CGRect(x: textField.frame.size.width + 8, y: 0, width: 44.0, height: viewLeftButton.frame.size.height))
        button.setTitle("Click", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        button.setTitleColor(.blue, for: .normal)

        viewLeftButton.addSubview(textField)
        viewLeftButton.addSubview(button)

        self.navigationItem.hidesBackButton = true
        let leftBarButton = UIBarButtonItem(customView: viewLeftButton)
        self.navigationItem.leftBarButtonItem = leftBarButton

推荐阅读