OSX 中的 SwiftUI 自定义文本字段 [英] SwiftUI customized text field in OSX

查看:34
本文介绍了OSX 中的 SwiftUI 自定义文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 SwiftUI 中为 Mac OSX 创建一个编辑视图.用户可以更改他的个人资料.目前我正在使用默认的 Text() 元素来查看他的当前值/设置.

I am creating a edit view in SwiftUI for Mac OSX. A user can change his profile. At the moment I am using default Text() elements to view his current values/settings.

现在我想创建一个编辑模式.我已经创建了一个按钮,用于切换编辑模式.如果编辑模式被激活,我用一个 TextField 替换每个 Text.

Now I want to create a edit mode. I already created a button, which toggles the edit mode. If the edit mode is activated, I replaced every Text with a TextField.

当我查看 Apple 的 Mac OSX 通讯录时,我发现他们使用了不同类型的文本字段(见图)

When I took a look at Apple's contact book for Mac OSX, I found out that they are using a different kind of Text Field (see image)

是否可以在 SwiftUI 和 OSX 中使用这种元素?他们叫什么,或者他们只是自定义的带边框的 TextFields?我找不到任何关于它们的官方文档.如果有人找到它,我会很高兴.

Is it possible to use this kind of element in SwiftUI and in OSX? What are they called or are they just customized TextFields with Border? I couldn't find any official documentation about them. If somebody finds it, I would be very happy.

推荐答案

嗯,一般来说,您只需要 PlainTextFieldStyle,但由于目前 SwiftUI 不允许关闭对焦环,因此有一些解决方法下面为所有文本字段全局禁用它.

Well, in general all you need is PlainTextFieldStyle, but as currently SwiftUI does not allow to turn off focus ring there is some workaround below to disable it globally for all text fields.

无论如何...我认为值得发布,所以这里是(使用 Xcode 11.3 测试)

Anyway... I think worth posting, so here it is (tested with Xcode 11.3)

extension NSTextField { // << workaround !!!
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

struct ContentView: View {
    @State private var text = ""
    var body: some View {
        HStack {
            Text("Mobil")
            TextField("", text: $text)
                .textFieldStyle(PlainTextFieldStyle())
                .padding(1)
                .background(RoundedRectangle(cornerRadius: 2).stroke(Color.white))
                .frame(width: 100)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }
}

这篇关于OSX 中的 SwiftUI 自定义文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆