Swift开发中UIScrollView嵌套UIStackView添加视图无显示问题求解
问题原因及修复方案
核心错误点
- 未给UIStackView添加和UIScrollView等宽的约束:UIScrollView的边锚点默认对应内容区域,仅绑定StackView的四边到ScrollView的四边,系统无法确定StackView的宽度要和ScrollView的可视宽度一致,会导致StackView宽度被压缩为0,内容无法展示。
- 手动设置的子视图frame无效:视图被加入到自动布局管理的UIStackView后,系统会忽略手动设置的frame,你没有给line1、line2添加明确的宽高约束,两个视图最终尺寸为0。
- 末尾手动调用
updateConstraints()、setNeedsLayout()属于冗余操作,不需要额外调用。
修复后的代码
scrollView = UIScrollView() view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor), scrollView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor), scrollView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), scrollView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor) ]) let line1 = UIView() line1.backgroundColor = .blue line1.translatesAutoresizingMaskIntoConstraints = false // 给子视图添加明确的高度约束,宽度会跟随StackView自动适配 line1.heightAnchor.constraint(equalToConstant: 1000).isActive = true let line2 = UIView() line2.backgroundColor = .green line2.translatesAutoresizingMaskIntoConstraints = false line2.heightAnchor.constraint(equalToConstant: 1000).isActive = true profile() stackView = UIStackView() stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .fill stackView.spacing = 10 scrollView.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: scrollView.topAnchor), stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), // 新增:绑定StackView宽度和ScrollView的可视宽度一致 stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor) ]) stackView.addArrangedSubview(line1) stackView.addArrangedSubview(line2)
内容的提问来源于stack exchange,提问作者cyj89317
相关产品推荐
相关产品推荐

