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?

More than 1 year has passed since last update.

【Swift】Label のサイズを画面サイズによって拡大縮小する。

Last updated at Posted at 2024-04-17

今回は Swift の Label のサイズを
画面サイズによって拡大縮小する方法を
紹介したいと思います。

この方法でサイズを拡大縮小すれば
タブレットで見た時に
文字サイズが小さくなる現象は
緩和されるハズです。

いわゆるレスポンシブ対応です。

ご自身のコードに
少しだけ追記するだけで実装出来ますので
簡単に適用できると思います。
是非実験してみて頂けると嬉しいです。

SwiftUI バージョンも最後に紹介します。


始めにサンプルコードを載せて
その使い方を説明します。

サンプルコード
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        changeAllFontSize()
    }
    
    func changeAllFontSize() {
        let views = getChild(view)
        for i in views {
            if let label = i as? UILabel {
                label.font = UIFont.systemFont(ofSize: pow(UIScreen.main.bounds.width * label.font.pointSize / 30, 0.5))
                //label.font = UIFont(name: "HiraginoSans-W7", size: pow(UIScreen.main.bounds.width * label.font.pointSize / 30, 0.5)) // 特定のフォントを使用したい場合                  
            }
        }
    }
    
    func getChild(_ view: UIView) -> [UIView] {
        var result: [UIView] = []
        
        result += (view.subviews)
        for i in view.subviews {
            result += getChild(i)
        }
        
        return result
    }
}

サンプルコードの
changeAllFontSize メソッドと
getChild メソッドを
ご自身のコードに追加して
viewDidLoad メソッドで
changeAllFontSize メソッドを
実行して使用します。

ofSize の部分の計算式を
良い具合の表示になるよう
調整して下さい。


以上 Swift で Label の文字サイズを
画面サイズで拡大縮小する方法を紹介しました。

適用するのは難しくないと思いますので
よろしければ実験して頂けると幸いです。

皆さんの開発の助けになれますように。
閲覧ありがとうございました。


追記

こちらのサイト
Swift でレスポンシブな配置を
する方法を載せています。

よろしければ参考にして頂けると幸いです。

また、この手法を用いた
Swift アプリ作成の練習で使ったデータを
無料配布致します。
よろしければ Swift 習得にご活用下さい。

https://drive.google.com/file/d/1rkaGgkvRcghH7e5GmBm9e9de8HJyAo9V/view?usp=sharing


追記

SwiftUI で適用したい場合は

一部抜粋
Text("button")
  .foregroundColor(Color.white)
  .font(.system(size: width / 5)) // width は親要素の横幅
  .fontWeight(.bold)

のように
文字サイズを親要素の
横幅を基準に調整して下さい。

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?