UIGestureRecognizer学习之UILongPressGestureRecognizer(长按)

本文详细介绍了iOS中UIGestureRecognizer的子类UILongPressGestureRecognizer,讲解了其属性,如何获取拖动信息,并给出了一个长按按钮实现删除功能的示例。
摘要由CSDN通过智能技术生成

属性

       UILongPressGestureRecognizer是UIGestureRecognizer的子类。
       UILongPressGestureRecognizer除了继承UIGestureRecognizer的属性外,还提供如下两个属性:

maximumNumberOfTouches: //设置该拖动手势处理器最多支持几个手指拖动。
minimumPressDuration: //指定用户至少在屏幕上按下多少秒才会触发该长按手势。该默认值为0.5

获取拖动

       除此之外,该手势处理器还提供了如下方法获取拖动的相关信息。

- translationInView: //获取该拖动手势在指定控件上的位移。该方法返回一个CGPoint结构体数据,该结构体中x变量的值代表了水平方向的位移,y变量的值代表了
你可以通过以下代码实现 UITextView 按复制粘贴的功能: ```swift // 设置允许复制和粘贴 textView.isSelectable = true textView.allowsEditingTextAttributes = true textView.textContainerInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) // 添加手势识别器 let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) textView.addGestureRecognizer(longPressGesture) // 手势识别器的响应函数 @objc func longPress(_ gestureRecognizer: UIGestureRecognizer) { // 获取按的位置 let point = gestureRecognizer.location(in: textView) // 获取按位置所在的字符索引 let characterIndex = textView.layoutManager.characterIndex(for: point, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // 判断按位置是否在文本范围内 if characterIndex < textView.textStorage.length { // 获取按位置所在的单词 let range = textView.tokenizer.rangeEnclosingPosition(TextViewPosition(document: textView.textStorage), with: .word, inDirection: UITextDirection(rawValue: 1)) let word = textView.text(in: range!) // 弹出菜单 let menuController = UIMenuController.shared if !menuController.isMenuVisible { let copyMenuItem = UIMenuItem(title: "复制", action: #selector(copyText(_:))) let pasteMenuItem = UIMenuItem(title: "粘贴", action: #selector(pasteText(_:))) menuController.menuItems = [copyMenuItem, pasteMenuItem] menuController.setTargetRect(CGRect(x: point.x, y: point.y, width: 0, height: 0), in: textView) menuController.setMenuVisible(true, animated: true) } } } // 复制文本 @objc func copyText(_ sender: Any) { UIPasteboard.general.string = textView.text(in: textView.selectedTextRange!) } // 粘贴文本 @objc func pasteText(_ sender: Any) { if let pasteString = UIPasteboard.general.string { let selectedRange = textView.selectedRange let mutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText) mutableAttributedString.replaceCharacters(in: selectedRange, with: NSAttributedString(string: pasteString)) textView.attributedText = mutableAttributedString } } ``` 这里使用了 `UITextView` 的 `UITextInputTokenizer` 对象来获取按位置所在的单词,并通过 `UIMenuController` 弹出菜单来实现复制和粘贴的功能。同时,需要在 `UITextView` 中设置 `isSelectable` 和 `allowsEditingTextAttributes` 属性为 `true`,并添加手势识别器来启用按功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fswy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值