检测用户是否从文本字段复制了文本

时间:2018-12-15 13:59:33

标签: swift copy uitextfield uipasteboard

我想使用用户从我的应用程序文本字段复制的单词。

我找到了以下代码:

    class MapPage extends StatefulWidget {
      @override
      _MapPageState createState() => _MapPageState();
    }

    class _MapPageState extends State<MapPage>
        with AutomaticKeepAliveClientMixin<MapPage> {

  @override
  Widget build(BuildContext context) {
    return Container(
      ///Getting size of the screen from [MediaQuery] inherited widget.
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: <Widget>[
          GoogleMap(
            onMapCreated: _onMapCreated,
            options: GoogleMapOptions(
              compassEnabled: true,
              mapType: MapType.normal,
              trackCameraPosition: true,
            ),
          ),

          ///If not enabled don't show ListView of places.
          toggleListView
              ? Positioned(
                  top: MediaQuery.of(context).size.height / 2,
                  left: 10,
                  child: Container(
                      height: MediaQuery.of(context).size.height / 4,
                      width: MediaQuery.of(context).size.width,
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        padding: EdgeInsets.all(5.0),
                        children: _places.map((place) {
                          return _placeCard(place);
                        }).toList(),
                      )),
                )
              : Container()
        ],
      ),
    );

  @override
  bool get wantKeepAlive => true;
}

但是从文本字段复制文本时不会调用'clipboardChanged'函数。

我使用Swift 4.2

1 个答案:

答案 0 :(得分:2)

此代码对我来说很好用:

    override func copy(_ sender: Any?) {
        super.copy()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged), name: UIPasteboard.changedNotification, object: nil)
    }

    @objc func clipboardChanged(){
        print("Cut/Copy Performed")
    }

有很多方法可以实现复制通知

1。 UIMenuController

显示一个菜单,其中包含“复制”,“剪切”,“粘贴”,“选择”和“选择所有”命令,位于选择的上方或下方。

引用:

https://developer.apple.com/documentation/uikit/uimenucontroller

https://nshipster.com/uimenucontroller/

2。 UIResponderStandardEditActions协议

响应者实现此非正式协议中声明的方法,以处理所选的菜单命令(例如copy:paste:)。由于您的UIViewController继承自确实符合UIResponder的{​​{1}},所以说UIResponderStandardEditActions时会出错。因此,只需直接实现所需的方法即可。

引用:https://developer.apple.com/documentation/uikit/uiresponderstandardeditactions

3。 UIPasteboard已更改通知

Redundant conformance

这是在粘贴板的更改计数(changeCount属性)增加的同时发生的。更改包括添加,删除和修改粘贴板项目。

引用:https://developer.apple.com/documentation/uikit/uipasteboard