6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Qiita全国学生対抗戦Advent Calendar 2022

Day 21

【SwiftUI】キーボードツールバーを実装する

Posted at

はじめに

DeepL翻訳アプリを使用していたらキーボードの上にツールバーが表示されていたので同じように実装してみました。
IMG_1843.PNG

サンプルアプリ

Simulator Screen Recording - iPhone 14 - 2022-12-21 at 21 30 53

実装

import SwiftUI

struct ContentView: View {
    @State var text: String = ""
    var body: some View {
        TextField(text: $text) {
            Text("テキストフィールド")
        }
        .textFieldStyle(.roundedBorder)
        .padding()
        .toolbar {
            toolbarItem
        }
    }

    var toolbarItem: ToolbarItem<(), HStack<TupleView<(Button<Text>, Spacer, Button<Text>)>>> {
        ToolbarItem(placement: .keyboard) {
            HStack {
                Button {
                    text = UIPasteboard.general.string ?? ""
                } label: {
                    Text("ペースト")
                }

                Spacer()

                Button {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                } label: {
                    Text(Image(systemName: "keyboard.chevron.compact.down"))
                        .font(.system(size: 15))
                }
            }
        }
    }
}

おわり

キーボードツールバーを実装することができました
意外とキーボードが閉じられないアプリが多いのでこれは忘れないようにしたいです。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?