【问题标题】:Remove custom spacing in UIStackView删除 UIStackView 中的自定义间距
【发布时间】:2019-10-25 07:51:25
【问题描述】:

我有一个包含三个子视图的堆栈视图:

stackView.spacing = 8.0

stackView.addArrangeSubview(view1)
stackView.addArrangeSubview(view2)
stackView.addArrangeSubview(view3)

有时,我会在 view2 之后添加自定义间距:

stackView.setCustomSpacing(24.0, after: view2)

现在,我想删除自定义间距。这可以使用 UIStackView 吗?我能想到的唯一方法是

stackView.setCustomSpacing(8.0, after: view2)

但如果我将 stackView 的间距更改为 8.0 以外的值,这将中断,因为在 view2 之后间距将保持 8.0。

【问题讨论】:

    标签: ios swift user-interface uistackview


    【解决方案1】:

    您应该重新创建具有特定间距的stackView,并将旧的替换为新的stackView

    【讨论】:

      【解决方案2】:
      let spacingView = UIView()
      
      [View1, View2, spacingView, View3].forEach { view in 
        stackView.addArrangeSubview(view)
      }
      

      当您想删除它时,只需从数组中删除 spacingView,您就可以根据自己的喜好调整 spacingView 的宽度和高度

      【讨论】:

        【解决方案3】:

        试试这个扩展:

        extension UIStackView {
        
            // remove all custom spacing
            func removeCustomSpacing() -> Void {
                let a = arrangedSubviews
                arrangedSubviews.forEach {
                    $0.removeFromSuperview()
                }
                a.forEach {
                    addArrangedSubview($0)
                }
            }
        
            // remove custom spacing after only a single view
            func removeCustomSpacing(after arrangedSubview: UIView) -> Void {
                guard let idx = arrangedSubviews.firstIndex(of: arrangedSubview) else { return }
                removeArrangedSubview(arrangedSubview)
                insertArrangedSubview(arrangedSubview, at: idx)
            }
        }
        

        简单地用作:

        myStackView.removeCustomSpacing()
        

        或者,如果您在多个视图上设置自定义间距,并且只想从一个视图中删除它,请使用:

        theStackView.removeCustomSpacing(after: view2)
        

        【讨论】:

          猜你喜欢
          • 2016-07-14
          • 2017-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多