[SwiftUI]TextFieldに文字数制限をかけるには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

TextFieldの文字数に制限をつける方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

TextFieldに文字数制限をかけるには、onReceiveを使います。

まず、Combineをインポートします。

import Combine

次に、TextFieldにonReceiveを付与します。

そして、TextFieldのonReceiveのクロージャーに、TextFieldが最大文字数を超えた際に、最大文字数までの文字列を代入する処理を追加します。

TextField("Your Text Here", text: $editingText)
    .onReceive(Just(editingText)) { _ in
        //最大文字数を超えたら、最大文字数までの文字列を代入する
        if editingText.count > textLimit {
            editingText = String(editingText.prefix(textLimit))
        }
    }
}

onReceiveを使えば、TextFieldに文字数制限をかけることができます。

使用例

以下は、使用例です。

struct ContentView: View {
    @State var editingText = ""

    let textLimit = 10 //最大文字数
    
    var body: some View {
        
        TextField("Your Text Here", text: $editingText)
            .onReceive(Just(editingText)) { _ in
                if editingText.count > textLimit {
                    editingText = String(editingText.prefix(textLimit))
                }
            }
    }
    
}

コメント

タイトルとURLをコピーしました