使用 TextEditor 在 SwifUI 中避免使用键盘 [英] Avoiding Keyboard in SwifUI with TextEditor

查看:30
本文介绍了使用 TextEditor 在 SwifUI 中避免使用键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重新创建 iOS 笔记应用程序的简单版本.请注意,我是一个完整的 Swift 新手.我目前的问题是我希望我的视图在键盘出现时向上移动.我已经实现了一些确实可以做到这一点的代码,但它有一些令人讨厌的错误.它首先将视图向上移动得太高,然后当您开始输入时,视图就在它应该在的位置.下面是一些表示的照片,以及我的代码:

I'm attempting to recreate a simple version of the iOS notes app. Mind you, I'm a complete Swift novice. My current issue is that I want my view to move up as the keyboard appears. I've implemented some code that does do this, but it has some nasty bugs. It first moves the view up WAY too high, then when you begin typing, the view is where it should be. Here are some photos for representation, as well as my code:

在键盘出现之前

当键盘第一次出现时

开始输入后

代码:

    class KeyboardResponder: ObservableObject {

    @Published var currentHeight: CGFloat = 0

    var _center: NotificationCenter
    
    @objc func keyBoardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                withAnimation {
                   currentHeight = keyboardSize.height
                    print("KEYBOARDSIZE.HEIGHT IN OBSERVER: \(keyboardSize.height)")
                }
            }
        print("KEYBOARD HEIGHT IN OBSERVER: \(currentHeight)")
        }
    @objc func keyBoardWillHide(notification: Notification) {
            withAnimation {
               currentHeight = 0
            }
        }

        init(center: NotificationCenter = .default) {
            _center = center
            _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
            _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        }
}

首先,有一个 KeyboardResponder 类,监听键盘的出现和消失(有一个发布的高度变量).

First, there is a KeyboardResponder class, listening for keyboard appearances and disappearances (with a published variable for its height).

        VStack {
        
       TextEditor(text: $content).padding(.all).foregroundColor(fontColors[self.color]).font(fontStyles[self.font])

        HStack {
            Spacer()
            Button(action: {
                self.show = false
            }) {
                Text("Cancel").foregroundColor(.gray).font(.headline)
            }
            
            Spacer()
            
            Button(action: {
                self.showPanel = true
            }) {
                Image(systemName: "textformat").font(.headline).foregroundColor(.white).padding(.all)
            }.background(Color.green).clipShape(Circle())
            
            Spacer()
            
            Button(action: {
                self.show.toggle()
                self.saveData()
            }) {
                Text("Save").foregroundColor(Color(UIColor.systemBlue)).font(.headline)
            }
            Spacer()
        }
        
    }.padding(.bottom, keyboardResponder.currentHeight)

这是视图,编辑器显示在照片中.在这个视图的顶部,我有@ObservedObject var keyboardResponder = KeyboardResponder().我试过 .padding(.bottom, keyboardResponder.currentHeight) 和 .offset(y: -keyboardResponder.currentHeight).有人知道是怎么回事吗?

This is the view, with the editor shown in the photos. At the top of this view I have @ObservedObject var keyboardResponder = KeyboardResponder(). I've tried both .padding(.bottom, keyboardResponder.currentHeight) as well as .offset(y: -keyboardResponder.currentHeight). Anyone know what's going on?

推荐答案

找到的解决方案:

我终于找到了一个有效的解决方案!我从https://augmentedcode.io/2020/03/29/revealing-content-behind-keyboard-in-swiftui/

I finally found a solution that works! I got this code from https://augmentedcode.io/2020/03/29/revealing-content-behind-keyboard-in-swiftui/

 fileprivate final class KeyboardObserver: ObservableObject {
    struct Info {
        let curve: UIView.AnimationCurve
        let duration: TimeInterval
        let endFrame: CGRect
    }
     
    private var observers = [NSObjectProtocol]()
     
    init() {
        let handler: (Notification) -> Void = { [weak self] notification in
            self?.keyboardInfo = Info(notification: notification)
        }
        let names: [Notification.Name] = [
            UIResponder.keyboardWillShowNotification,
            UIResponder.keyboardWillHideNotification,
            UIResponder.keyboardWillChangeFrameNotification
        ]
        observers = names.map({ name in
            NotificationCenter.default.addObserver(forName: name,
                                                   object: nil,
                                                   queue: .main,
                                                   using: handler)
        })
    }
 
    @Published var keyboardInfo = Info(curve: .linear, duration: 0, endFrame: .zero)
}
 
fileprivate extension KeyboardObserver.Info {
    init(notification: Notification) {
        guard let userInfo = notification.userInfo else { fatalError() }
        curve = {
            let rawValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int
            return UIView.AnimationCurve(rawValue: rawValue)!
        }()
        duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
    }
}


struct KeyboardVisibility: ViewModifier {
    @ObservedObject fileprivate var keyboardObserver = KeyboardObserver()
 
    func body(content: Content) -> some View {
        GeometryReader { geometry in
            withAnimation() {
                content.padding(.bottom, max(0, self.keyboardObserver.keyboardInfo.endFrame.height - geometry.safeAreaInsets.bottom))
                    .animation(Animation(keyboardInfo: self.keyboardObserver.keyboardInfo))
            }
        }
    }
}
 
fileprivate extension Animation {
    init(keyboardInfo: KeyboardObserver.Info) {
        switch keyboardInfo.curve {
        case .easeInOut:
            self = .easeInOut(duration: keyboardInfo.duration)
        case .easeIn:
            self = .easeIn(duration: keyboardInfo.duration)
        case .easeOut:
            self = .easeOut(duration: keyboardInfo.duration)
        case .linear:
            self = .linear(duration: keyboardInfo.duration)
        @unknown default:
            self = .easeInOut(duration: keyboardInfo.duration)
        }
    }
}

extension View {
    func keyboardVisibility() -> some View {
        return modifier(KeyboardVisibility())
    }
}

然后只需将修饰符添加到您要使用键盘向上移动的视图中,就像这样 .keyboardVisibility()

Then just add the modifier to the view you want to move up with the keyboard like so .keyboardVisibility()

这篇关于使用 TextEditor 在 SwifUI 中避免使用键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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