1
2

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 5 years have passed since last update.

UIStackViewのspacingを個別に指定する方法

Last updated at Posted at 2018-12-25

UIStackViewのspacing

UIStackViewのspacingは一度値を入れるとずっとその幅でレイアウトされます。
これを一つのstackViewで、viewとviewの間ごとに空白の幅を指定できるようにします。

手順

1. sizeだけを持つUIViewのカスタムクラスを作る

以下をコピペ

import UIKit

final class SpacerView: UIView {
    
    private let space: CGFloat
    
    init(_ space: CGFloat) {
        self.space = space
        super.init(frame: .zero)
    }
    
    override var intrinsicContentSize: CGSize {
        return .init(width: space, height: space)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

2. 使う

.spacingの指定はせず、SpacerViewinitializerからサイズの指定をする

let stackView = UIStackView(arrangedSubviews: [
        view, SpacerView(5), view, SpacerView(10), view, SpacerView(20), view
])
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?