点击文本字段右键时如何显示xib视图
Posted
技术标签:
【中文标题】点击文本字段右键时如何显示xib视图【英文标题】:how to show xib view when tap on textfield right button 【发布时间】:2019-12-31 11:19:26 【问题描述】:我想在点击文本字段右键时显示一个弹出视图,我试过了 下面的代码,但点击文本字段右键时视图不显示。 ,我用“CustomeView”类名创建了xib视图,如下所示 ,尝试在警报视图中加载
class ViewController: UIViewController, UITextFieldDelegate
let textFieldRightButton = UIButton(type: .infoLight)
var textFieldOne:UITextField? = nil
var alertview:UIView? = nil
override func viewWillAppear(_ animated: Bool)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute:
self.showAlertViewWithTextField(title: "Test", msg: "Test Custome View", okActionTitle: "continue", cancelActionTitle: "Cancel", success:
print("Continue")
)
print("Cancel")
)
func showAlertViewWithTextField(title: String, msg: String, okActionTitle:String, cancelActionTitle:String, success: (() -> Void)? , cancel: (() -> Void)?)
let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert)
alertview = alert.view
textFieldRightButton.tintColor = UIColor.red
alert.addTextField
(textField) in
textField.placeholder = "Enter text."
textField.delegate = self
textField.rightViewMode = .always
textField.rightView = self.textFieldRightButton
textFieldOne = alert.textFields?.first
textFieldRightButton.addTarget(self, action: #selector(showPopupMsg), for: .touchUpInside)
let successAction: UIAlertAction = UIAlertAction(title: okActionTitle, style: .destructive)
action -> Void in
success?()
let cancelAction: UIAlertAction = UIAlertAction(title: cancelActionTitle, style: .cancel)
action -> Void in
cancel?()
alert.addAction(successAction)
alert.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
@objc func showPopupMsg()
alertview?.addSubview(CustomeView(frame: CGRect(x: textFieldOne!.frame.minX, y: textFieldOne!.frame.minX, width: 100, height: 50)))
下面是我的自定义视图
class CustomeView: UIView
@IBOutlet var contentView: UIView!
@IBOutlet weak var messageText: UILabel!
override init(frame: CGRect)
super.init(frame: frame)
commonInit()
required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
commonInit()
private func commonInit()
Bundle.main.loadNibNamed("CustomeView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
如何在视图控制器中显示此 nib 视图?
【问题讨论】:
提示:IBOutlet 连接 我连接了 iboulets。 今天是什么日子?免费投票日?顺便说一句,这是一个很好的答案:***.com/a/26326006/8374890 你建立了一个 IBOutlet 连接到什么!? 在xib中标注和查看 【参考方案1】:我尝试了您的代码 sn-p,但出现了错误的访问错误。尝试删除该 xib 文件的自定义类 (CustomeView) 并在该 xib 文件的 File's Owner
中设置 CustomeView
视图类。还要检查你的messageText
和contentView
出口对象类型应该是File's Owner
。
【讨论】:
以上是关于点击文本字段右键时如何显示xib视图的主要内容,如果未能解决你的问题,请参考以下文章
iOS 如何在滚动视图/webview 上实现点击手势以“敲出”文本字段?
当点击 UITextField 时,加载 nib 文件以充当自定义键盘