You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为垂直轴、leading对齐的UIStackView添加自定义水平间距?

UIStackView 自定义间距布局问题

我有一个垂直方向的UIStackView,其中包含一个标题标签和另一个水平方向的UIStackView(图标栈视图),需要为它们添加自定义间距。该布局参考Apple官方文档中UIStackView的「Define the stack’s size along its axis」部分。此垂直轴StackView作为UICollectionViewCell的子视图,上下边缘固定在contentView的上下边缘,leading边缘与contentView的leading边缘偏移24点。

我的实现代码:

func setUp() {
    
    titleView = UILabel()
    femaleIcon = UIImageView()
    maleIcon = UIImageView()
    femaleIcon.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(switchFemaleIcon)))
    
    femaleIcon.contentMode = .scaleAspectFit
    maleIcon.contentMode = .scaleAspectFit
    
    maleIcon.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(switchMaleIcon)))
    
    let iconStackView = UIStackView(arrangedSubviews: [
        femaleIcon,
        maleIcon
    ])
    
    iconStackView.axis = .horizontal
    iconStackView.translatesAutoresizingMaskIntoConstraints = false
    
    iconStackView.setCustomSpacing(50, after: femaleIcon)
    
    iconStackView.backgroundColor = .yellow
    
    let stackView = UIStackView(arrangedSubviews: [
        titleView,
        iconStackView
    ])
    
    stackView.axis = .vertical
    stackView.alignment = .leading
    contentView.addSubview(stackView)
    
    stackView.backgroundColor = .magenta
    
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    
    stackView.setCustomSpacing(14, after: titleView)

    NSLayoutConstraint.activate([
        femaleIcon.widthAnchor.constraint(equalToConstant: 30),
        femaleIcon.heightAnchor.constraint(equalToConstant: 48),
        
        maleIcon.widthAnchor.constraint(equalToConstant: 36),
        maleIcon.heightAnchor.constraint(equalToConstant: 36.5),
        
        stackView.topAnchor.constraint(equalTo: contentView.topAnchor),
        stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
    ])
}

预期布局效果:

预期布局效果

内容的提问来源于stack exchange,提问作者Asaad Jaber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:40:04