【问题标题】:How to implement a Longpress Gesture on a UITextView如何在 UITextView 上实现长按手势
【发布时间】:2018-01-21 16:15:23
【问题描述】:

是否可以在 UITextView 上实现长按手势?基本上,如果用户在文本视图上点击一次,我希望他/她能够编辑文本。但是,如果他/她点击并按住文本视图(比如说两秒钟),会执行一个动作吗?如果答案是肯定的,请告诉我如何实现这一目标?

按照 kchromik 的说法,以下是我的问题的解决方案:

(1) 第一步是在 ViewController 类开始之前定义如下扩展:

extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizer (_ gestureRecognizer: UIGestureRecognizer, shouldRecognizerSimultaneouslyWithotherGestureRecognizer: UIGestureRecognizer) -> Bool { return true}}

(2) 第二步是将主故事板中的 UITextView Outlet 链接到 swift 代码文件:

@IBOutlet weak var testTextView: UITextView!

(3) 第三步是从对象库中将 GestureRecognizer 拖放到要在其上实现 Longpress Gesture Recognizer 的 UITextView 之上。

(4)第四步,在viewDidLoad()下添加如下代码{

    let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))

    uilpgr.minimumPressDuration = 2

    testTextView.addGestureRecognizer(uilpgr)

uiplgr.delegate = self

}

(5) 最后一步是定义要与之前定义的 Longpress 手势识别器一起使用的函数:

func longpress(gestureRecognizer: UIGestureRecognizer) {

    print("Long tap") // Execute what you want to do

}

【问题讨论】:

  • 用您迄今为止尝试过的内容更新您的问题。清楚地解释您遇到的问题。
  • 您的代码是关于向标签添加手势,而不是文本视图。你应该解决你的问题。

标签: ios swift uitextview uilongpressgesturerecogni


【解决方案1】:

默认情况下,UILabel 禁用用户交互。在您的viewDidLoad 中尝试testLabel.isUserInteractionEnabled = true 或在情节提要中启用它:

更新

如果您UIView 有自己的手势识别器,您可以实现以下委托:

extension ViewController: UIGestureRecognizerDelegate {
  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
  }
}

而且你不要忘记设置uilpgr.delegate = self

【讨论】:

  • 非常感谢以上解决了我的 UILabel 问题。但是,当我尝试做同样的事情但使用 UITextView 而不是 UILabel 时,每次我长按 UITextView 时,除了将我置于 UITextView 内的编辑模式之外,什么都没有发生。关于 UITextView 有什么需要我首先做的吗?
  • 你的意思是UITextField还是UITextView
  • 但是你可以做的是:extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } 而且你别忘了设置uilpgr.delegate = self
  • 我的意思是 UITextView
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多