Flutter绘图App中如何禁用Apple Pencil的Scribble及检测笔身点击?
适配iPad Apple Pencil的Flutter绘图应用问题解决方案
一、自动禁用Apple Pencil Scribble功能
Flutter本身没有直接控制Scribble的API,需通过iOS原生代码实现App启动时自动禁用:
- 打开iOS项目的
AppDelegate.swift文件 - 在
didFinishLaunchingWithOptions方法中添加代码,禁用Flutter视图的Scribble交互:
import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // 禁用Apple Pencil Scribble功能 if let flutterView = window?.rootViewController?.view as? FlutterView { flutterView.scribbleInteraction?.isEnabled = false } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
App启动后会自动关闭Scribble,无需用户手动在系统设置中操作。
二、检测Apple Pencil笔身点击操作
Flutter无法直接捕获笔身按键事件,需通过iOS原生监听远程控制事件,再通过MethodChannel传递到Flutter层:
iOS端代码(AppDelegate.swift)
import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { private let pencilChannel = FlutterMethodChannel(name: "pencil_control", binaryMessenger: UIApplication.shared.delegate as! FlutterBinaryMessenger) override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // 开启远程控制事件监听 application.beginReceivingRemoteControlEvents() return super.application(application, didFinishLaunchingWithOptions: launchOptions) } override func remoteControlReceived(with event: UIEvent?) { guard let event = event, event.type == .remoteControl else { return } // Apple Pencil单次点击对应远程控制的播放/暂停事件 if event.subtype == .remoteControlPlayPause { pencilChannel.invokeMethod("pencil_button_tapped", arguments: nil) } } }
Flutter端代码
import 'package:flutter/services.dart'; void main() { runApp(const MyApp()); // 初始化Apple Pencil按键监听 _initPencilButtonListener(); } void _initPencilButtonListener() { const MethodChannel _pencilChannel = MethodChannel('pencil_control'); _pencilChannel.setMethodCallHandler((MethodCall call) async { if (call.method == 'pencil_button_tapped') { // 在这里实现工具切换逻辑,比如切换到橡皮擦 print("Apple Pencil按键被点击,切换至橡皮擦"); // 你的工具切换代码 } }); }
注意:Apple Pencil的按键事件会被识别为系统远程控制的播放/暂停事件,如果App内有音频播放功能,需额外处理避免冲突。
内容的提问来源于stack exchange,提问作者Kevin Yang
相关产品推荐
相关产品推荐

