如何找到带有自定义标签或可访问性标识符的SwiftUI视图?

问题描述

以下是示例代码(使用Introspect包):

import SwiftUI
import Introspect

struct ContentView: View {
    let tag = 123
    let id = "abc"

    var body: some View {
        ScrollView {
            Text("Hello,world!")
                .tag(tag)
                .accessibility(identifier: id)
        }.introspectScrollView { (scrollView) in
            /// - Note: find with tag
            if scrollView.viewWithTag(tag) != nil {
                print("OK")
            } else {
                print("NOT OK")
            }
            /// - Note: find with accessibilityIdentifier
            if findViewWithID(id,in: scrollView) != nil {
                print("OK")
            } else {
                print("NOT OK")
            }
        }
    }

    func findViewWithID(_ id: String,in uiView: UIView) -> UIView? {
        if uiView.accessibilityIdentifier == id {
            return uiView
        }
        for view in uiView.subviews {
            if let view = findViewWithID(id,in: view) {
                return view
            }
        }
        return nil
    }
}

为什么tagaccessibilityIdentifier无法正确传播到基础视图层次结构?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)