如何将滚动视图的大小设置为与视图相同的大小

问题描述 投票:0回答:1

我有一个视图,并且在视图内部有一个滚动视图。我以编程方式设置了滚动视图。但是由于某些原因,scrollview并不完全适合视图。滚动视图与视图具有相同的框架。但是由于某种原因,它无法正常工作。

enter image description here

白色视图是滚动视图所在的视图。滚动视图是绿色视图。我将背景色设置为绿色。在滚动视图中有一个图像视图。

我的代码:

      var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = false
        scrollView.alwaysBounceHorizontal = false
        scrollView.isPagingEnabled = true
        return scrollView
    }()


   scrollView.backgroundColor = .green
        scrollView.frame = contentView.frame
        contentView.addSubview(scrollView)

var frame = CGRect.zero
    func viewTutorial() {
        for i in 0..<arrayOfTutorilImages.count {
        frame.origin.x = scrollView.frame.size.width  * CGFloat((i))
            frame.size = scrollView.frame.size

            let imageView = UIImageView(frame: frame)
            imageView.image = UIImage(named: arrayOfTutorilImages[i])
            imageView.contentMode = .scaleAspectFit
            self.scrollView.addSubview(imageView)
        }

        scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(arrayOfTutorilImages.count)), height: scrollView.frame.size.height)
        scrollView.delegate = self
    }

extension TutorialViewController: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
        pageControl.currentPage = Int(pageNumber)
    }
}
ios swift imageview uiimage scrollview
1个回答
0
投票

我建议您使用约束:

        self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
        self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
        self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)

如果您喜欢UIView + Helpers,则可以为此创建一个辅助方法,并且仅使用一行。

extension UIView {
    public func pinToEdges(of view: UIView,
                           topConstant: CGFloat = 0,
                           leadingConstant: CGFloat = 0,
                           bottomConstant: CGFloat = 0,
                           trailingConstant: CGFloat = 0) {

        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant),
            self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: leadingConstant),
            self.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: bottomConstant),
            self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: trailingConstant),
            ])
    }
}

然后使用:

self.collectionView.pinToBounds(self.view)

当然要记住将translatesAutoresizingMaskIntoConstraints设置为false

© www.soinside.com 2019 - 2024. All rights reserved.