iOS 15 UITextField長按菜單支持live text 掃描插入文字功能

1.需求背景

iOS15上有一個(gè)非常好用的scan text (也可以叫l(wèi)ive text)功能,如果能加上,用于掃描文本OCR(光學(xué)字符識(shí)別Optical Character Recognition),直接插入到textField里還是很方便的。

ios15-iphone12-pro-photos-copy-text.png

2.為什么目前不支持?

因?yàn)槲矣玫淖远xtextField,沒有針對(duì)scan text進(jìn)行適配。我查閱了很多關(guān)于iOS15 OCR的資料。但是給textField長按菜單,加上scan text的內(nèi)容沒有找到,大體都說自定義長按菜單需要在

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool

這個(gè)函數(shù)里去添加對(duì)應(yīng)的action,然后

override func target(forAction action: Selector, withSender sender: Any?) -> Any?

這個(gè)函數(shù)里也要去做對(duì)應(yīng)方法的實(shí)現(xiàn),才能有對(duì)應(yīng)的功能。

那么scan text對(duì)應(yīng)的是哪個(gè)selector方法呢?

UIResponderStandardEditActions這個(gè)類里,并沒有看到和OCR或者scan text相關(guān)的方法。然后我翻閱官方文檔,找到了個(gè)很類似OCR的API

extension UIResponder {
    @available(iOS 15.0, *)
    open func captureTextFromCamera(_ sender: Any?)
}

試了下,果然就是這個(gè)玩意兒

所以如果你要你的自定義textField或者textview擁有scan text OCR的能力,那么應(yīng)該如下實(shí)現(xiàn)。

3.實(shí)現(xiàn)

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if #available(iOS 15.0, *) {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) ||
            action == #selector(UIResponder.captureTextFromCamera(_:)){
            return true
        }
    } else {
        return super.canPerformAction(action, withSender: sender)
    }
    return super.canPerformAction(action, withSender: sender)
}
override func target(forAction action: Selector, withSender sender: Any?) -> Any? {
    if #available(iOS 15.0, *) {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) ||
            action == #selector(UIResponderStandardEditActions.select(_:)) ||
            action == #selector(UIResponderStandardEditActions.selectAll(_:)) ||
            action == #selector(UIResponder.captureTextFromCamera(_:)) {
            return super.target(forAction: action, withSender: sender)
        }
    } else {
        // Fallback on earlier versions
        if action == #selector(UIResponderStandardEditActions.paste(_:)) ||
            action == #selector(UIResponderStandardEditActions.select(_:)) ||
            action == #selector(UIResponderStandardEditActions.selectAll(_:))
            {
            return super.target(forAction: action, withSender: sender)
        }
    }
    return nil
}

4.限制

4.1 版本和設(shè)備限制

只支持iOS15+,且iPhone Xs及以后的設(shè)備。如下是官方說明

For this property to be true, the device must have the A12 Bionic chip or later.

所以我們需要判斷iOS 系統(tǒng)版本是iOS15,且支持OCR。

4.2 如何判斷是否支持live text

一種是ImageAnalyzer.isSupported,如果是iOS 16就用這個(gè)判斷,需要引入import VisionKit 這個(gè)visionKit。

另一種是利用實(shí)例化方法, canPerformAction(_:withSender:) ,官方的說法如下:

To determine whether the data scanner runs on the user’s device, pass captureTextFromCamera(_:) to the canPerformAction(_:withSender:) method.

例如

if UITextField().canPerformAction(#selector(UIResponder.captureTextFromCamera(_:)), withSender: self) { ... }

我之前以為直接用button的實(shí)例,來判斷就可以了,居然不生效。一直返回false,我還不清楚說明原因。但是用上面這種,直接聲明一個(gè)UITextField的實(shí)例來判斷,就正常了,真的神奇。如果是在UIController里面,用下面的代碼也可以:

if #available(iOS 15.0, *), self.canPerformAction(#selector(UIResponder.captureTextFromCamera(_:)), withSender: self) {
    print("support live text")
    button.addTarget(self, action: #selector(UIResponder.captureTextFromCamera(_:)), for: .touchUpInside)
} else {
    print("this device is not support live text")
}

所以這個(gè)條件,也是有點(diǎn)迷。

5.擴(kuò)展運(yùn)用 -- 如何自定義一個(gè)按鈕,調(diào)用scan text識(shí)別文字功能?

自定義的按鈕,和textField最大的不同,就是textField默認(rèn)遵循了UIKeyInput or UITextInput 這兩個(gè)中的某個(gè)協(xié)議,所以我們自定定義的按鈕,那么我們要自己去遵循至少,這兩個(gè)之一的協(xié)議,然后實(shí)現(xiàn)對(duì)應(yīng)的代理方法,否則會(huì)崩潰。官方說明如下:

To receive callbacks from the data scanner, the responder should conform to either the UIKeyInput or UITextInput protocol. If it conforms to UIKeyInput, the scanner calls the insertText: protocol method. If it conforms to UITextInput, the scanner calls the setMarkedText(_:selectedRange:) and unmarkText() protocol methods.

class ViewController: UIViewController, UIKeyInput {
        var hasText: Bool = false
        
    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton.init(frame: CGRect(x: 100, y: 200, width: 100, height: 100))
                if #available(iOS 15.0, *), self.canPerformAction(#selector(UIResponder.captureTextFromCamera(_:)), withSender: self) {
            print("support live text")
            button.addTarget(self, action: #selector(UIResponder.captureTextFromCamera(_:)), for: .touchUpInside)
        } else {
            print("this device is not support live text")
        }
        button.backgroundColor = .red
        view.addSubview(button)
    }
    
    func deleteBackward() {
        
    }
    
    func insertText(_ text: String) {
        //ORC scan text的 insert Text 按鈕回調(diào)
        print("OCR 掃描到的文字是: \(text)")
        labelTest.text = text
    }
}

參考文獻(xiàn):

https://developer.apple.com/documentation/uikit/uiresponder/3778577-capturetextfromcamera?changes=_5

https://developer.apple.com/documentation/visionkit/imageanalyzer/3974561-issupported

https://stackoverflow.com/questions/69702884/how-to-know-a-device-is-available-to-use-capturetextfromcamera-api/73995804#73995804

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容