首页 > 解决方案 > UIScrollView 第二次不显示

问题描述

我正在使用 SpriteKit 构建一个应用程序,因此我只使用一个 ViewController 来添加或删除子视图。而且我总是添加一个子视图的新实例。

当我尝试添加 aUIScrollView时,它在我第一次添加时显示得非常好。但是,在我删除UIScrollView并再次添加它(的新实例UIScrollView)之后。UIScrollView没有出现。

第一次和第二次的框架UIScrollView和里面是一样的。UIStackView

我不太明白为什么它不能正常工作。我猜它与自动布局有关,但同样,第一次和第二次添加的框架是相同的。而且,我不想在这里实现自动布局。

这是课程:

class StoreScrollV: UIScrollView {
    override init(frame: CGRect) {
        super.init(frame: rectOfEntireScreen)
        self.bounds.size = CGSize(width: 300, height: 300)
        self.contentSize = CGSize(width: 1000, height: 300)
        self.tag = 100
        
        let stackView = UIStackView()
        self.addSubview(stackView)
        stackView.tag = 111
        stackView.frame.size = CGSize(width: 1000, height: 300)
        stackView.frame = stackView.toCenter() 
        //custome function that move the view to the center of its parent with the same size.

        stackView.axis = .horizontal

        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.translatesAutoresizingMaskIntoConstraints = false
        
        let imageV1 = UIImageView(image: UIImage(named: "ballCat"))
        stackView.addArrangedSubview(imageV1)
        
        let imageV2 = UIImageView(image: UIImage(named: "ballChicken"))
        stackView.addArrangedSubview(imageV2)
     
        stackView.spacing = 10;
        stackView.distribution = .equalCentering
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMove(toWindow newWindow: UIWindow?) {
        if newWindow != nil {
//            joinAnimationFromTop(view: self)
        } else {
//            leaveAnimationResetToTop(view: self)
        }
    } 
}

这是我添加它的方法:(UIScrollView在另一个UIView被添加的内部)

let storePage = StoreView() //another customized UIView frame is the entire screen at 0,0.
let scrV = StoreScrollV()

storePage.addSubview(scrV)
scrV.frame = scrV.toCenter()
//custome function that move the view to the center of its parent with the same size.

VC.addSubview(viewWithScrollV)

层次调试第二次添加ScrollView

层次调试第二次添加ScrollView

标签: iosswiftuiscrollview

解决方案


        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.translatesAutoresizingMaskIntoConstraints = false

改成

        stackView.translatesAutoresizingMaskIntoConstraints = true
        self.translatesAutoresizingMaskIntoConstraints = true

问题已解决。

scrollView 的框架实际上是 (0,0,0,0)。我没有意识到这一点,因为我在调试的时候,在init函数的最后打印出了scrollView的frame。

因此框架是正确的。当我使用 Kamil 建议的视图层次调试时,我意识到框架一直是错误的。

但是,我仍然不明白为什么如果框架是(0,0,0,0)它甚至会在第一次出现。


推荐阅读