uistackView中的隐藏子视图超出屏幕

我试图为uistackView的已安排的子视图进行动画,

UIView.animate(withDuration: 3, delay: 0) {
    self.stackView.subviews.forEach({ $0.isHidden = true })
    self.stackView.updateConstraintsIfNeeded()
    self.stackView.layoutIfNeeded()
    self.view.layoutIfNeeded()
} completion: { (_) in
    self.children.forEach({ $0.removeFromParent() })
    completion()
}

问题是屏幕上宽度展开的动画(超出屏幕界限)。

这是对视图的设置方式:

scrollView = {
    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    return scrollView
}()

stackView = {
    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.distribution = .fill
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    return stackView
}()

contentView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

contentView.addSubview(stackView)
scrollView.addSubview(contentView)
view.addSubview(scrollView)

scrollView.showsVerticalScrollIndicator = false
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true

stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20).isActive = true
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -50).isActive = true

问答:如何以这样的方式为其动画,它在动画期间不会改变宽度?

回答 1

  1. 赞同 1

    I don't know if this is a weird issue of the UIStackViewor它是一些目的,但是:施加一个“无形”UIView你的UIStackView修复问题。标记它,所以在隐藏它仍然可见的其他元素时:

    let imposterView = UIView()
    imposterView.tag = 999
    stackView.addArrangedSubview(imposterView)
    

    课程处理您的隐藏逻辑相应:

    stackView.subviews.forEach({
         if $0.tag != 999 {
             $0.isHidden = true
         }
    })
    

    This solves the problem of the width changing during animation, thank you very much!FFRITZ