[SwiftUI]セグメントピッカーの選択時のテキストサイズを設定

SwiftUI

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

SegmentedPickerStyleのPickerの選択れている項目の文字サイズを設定する方法を紹介します。

スポンサーリンク

方法

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

SegementedPickerの選択時の文字サイズを設定するには、UISegmentedControlを使います。

まず、initメソッドやonAppear修飾子などで、「UISegmentedControl.appearance().setTitleTextAttributes()」を呼び出します。

そして、「setTitleTextAttributes」の第1引数に「[.font : UIFont.systemFont(ofSize : サイズ)]」、第2引数「for」に「.selected」を指定します。

//UIFont.systemFontの引数「ofSize」に文字サイズを指定
UISegmentedControl.appearance().setTitleTextAttributes(
    [.font : UIFont.systemFont(ofSize: textSize)], for: .selected
)

UISegmentedControlを使うことで、セグメントのPickerの選択時の文字サイズを設定することができます。

使用例

struct ContentView: View {
    
    @State private var selectedIndex = 0
    
    init() {
        UISegmentedControl.appearance().setTitleTextAttributes(
            [.font : UIFont.systemFont(ofSize: 20)], for: .selected
        )
    }
    
    var body: some View {
        VStack {
            
            Picker(selection: $selectedIndex, label: Text("Select").foregroundColor(.red)) {
                ForEach(0..<5) {
                    Text("Item \($0)")
                }
            }
            .pickerStyle(SegmentedPickerStyle())
        }
    }
}

コメント

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