Home > OS >  scrollView depends on content
scrollView depends on content

Time:07-13

i have o content on my VC: TitleLabel and DescriptionLabel, sometimes i have very long description and it is not placed in my VC, so i decided to add scrollView there. But scroll is not working, and how can i calculate scrollView size depends on description?

lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        return scrollView
    }()
func configureUI() {
        view.addSubview(scrollView)
        
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide)
          make.leading.trailing.equalTo(self.view.safeAreaLayoutGuide)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide)
        }
        
        scrollView.addSubview(titleLabel)
        scrollView.addSubview(descriptionLabel)

        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide)
            make.left.right.equalTo(self.view.safeAreaLayoutGuide)
        }

        descriptionLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(self.titleLabel.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide)
        }
        
    }

CodePudding user response:

To make a dynamic height and vertically scrollable, embed those labels in a view:

func configureUI() {
    self.view.addSubview(scrollView)
    
    scrollView.snp.makeConstraints { (make) in
        make.top.bottom.equalTo(self.view.safeAreaLayoutGuide)
        make.leading.trailing.equalTo(self.view.safeAreaLayoutGuide)
    }
    
    scrollView.addSubview(contentView)
    
    contentView.snp.makeConstraints { (make) in
        make.width.equalToSuperview()
        make.centerX.top.bottom.equalToSuperview()
    }
    
    _ = [titleLabel, descriptionLabel].map { self.contentView.addSubview($0)}
    
    
    titleLabel.text = "Sample Title"
    descriptionLabel.text = " << LONG TEXT >>"
    
    titleLabel.snp.makeConstraints { (make) in
        make.leading.top.trailing.equalToSuperview()
    }
    
    descriptionLabel.snp.makeConstraints { (make) in
        make.top.equalTo(titleLabel.snp.bottom)
        make.leading.trailing.equalToSuperview()
        make.bottom.equalToSuperview()
    }
}
  • Related