0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

# [UIKit] UIStackView内のSubview間のスペースをカスタマイズする

Posted at

完全自分用の学習備忘録。

UIStackView を使用している際、ビュー間の間隔を柔軟に調整したいことがあります。setCustomSpacing(_:after:) メソッドを使用することで、特定のビューの直後にカスタム間隔を設定できます。

お恥ずかしながら、私はこれまで、こんなメソッドがあることを知りませんでした… 「SpacerView」という名のUIViewをわざわざ生成して、特定のビュー間の間隔を調整していました…

やりたいこと↓

Simulator Screenshot - iPhone 11 Pro Max - 2025-01-09 at 13.03.50.png

setCustomSpacing(_:after:) の基本構文

func setCustomSpacing(
    _ spacing: CGFloat,
    after arrangedSubview: UIView
)
  • spacing: 指定する間隔(ポイント単位)。
  • arrangedSubview: このビューの直後に間隔を設定します。

基本的な使い方

以下の例では、UIStackView に 3 つのラベルを配置し、2 番目のラベルの直後にカスタム間隔を設定します。

コード

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        // UIStackView の作成
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 10 // デフォルトの間隔
        stackView.layer.borderColor = UIColor.black.cgColor
        stackView.layer.borderWidth = 3.0
        stackView.translatesAutoresizingMaskIntoConstraints = false

        // UIView の作成
        let view1 = UIView()
        view1.backgroundColor = .systemBlue

        let view2 = UIView()
        view2.backgroundColor = .systemGreen

        let view3 = UIView()
        view3.backgroundColor = .systemRed
        
        let view4 = UIView()
        view4.backgroundColor = .systemPink

        // サイズを設定
        [view1, view2, view3, view4].forEach { view in
            view.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                view.heightAnchor.constraint(equalToConstant: 100),
                view.widthAnchor.constraint(equalToConstant: 100)
            ])
        }

        // スタックビューに UIView を追加
        stackView.addArrangedSubview(view1)
        stackView.addArrangedSubview(view2)
        stackView.addArrangedSubview(view3)
        stackView.addArrangedSubview(view4)

        // カスタム間隔を設定
        stackView.setCustomSpacing(50, after: view2)
        stackView.setCustomSpacing(100, after: view3)

        // スタックビューをビューに追加
        view.addSubview(stackView)

        // レイアウトの設定
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?