0
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?

SwiftUIで異なるViewの幅を保持して右寄せを行う

0
Posted at

SwiftUIにおいて、View内の最大幅を持つViewに合わせて右センタリングしたい場合、alignmentを指定ことで簡単に実現できる。

List内のコンテンツで、この幅揃えを均等に行いたい場合、まず思いつくのはframeによる幅固定だ。この例では問題なく見える。

だが、これはローカライズ時などに問題が発生する。言語によって長さは違うため、固定値だと見切れや不自然な余白が起きる。

↑この例では最も長い"Long string"という文字の前に1文字分の不自然な余白がある。

これを解決するには、各View幅を比較して最大値をframeに指定することで、幅が異なっても自動で最大の幅に合わせて右寄せにしてくれる。

@State var uniWidth:CGFloat = 200
@State var widthList:[CGFloat] = []

VStack(alignment:.trailing) {
    Text("大きい文字列")
        .onGeometryChange(for: CGFloat.self, of: { geometry in
            geometry.size.width
        }, action: { newWidth in
            widthList.append(newWidth)
            uniWidth = (widthList.max() ?? uniWidth)
        })
        .lineLimit(1)
}
.frame(width:uniWidth,alignment:.trailing)

(Textの幅が動的変化しない前提。変化する場合は変更の監視時に古い値を配列から削除する処理の追加が必要。)

なおiPadOS/macOSではTableを使えば簡単だが、肝心のiOSでの表示が横並びではない。

0
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
0
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?