使用自动布局的水平UIScrollView

时间:2017-06-05 10:27:32

标签: ios objective-c uiscrollview autolayout

我已经尝试了很长一段时间了,并在SO和一些视频教程上经历了很多帖子。我想要创建的是一个水平滚动视图,其中包含一些按钮,如下所示:enter image description here

我的视图层次结构如下:

  • 查看控制器
    • 查看
      • 滚动视图
        • 查看
          • 按钮

我已将顶部,前导,尾随,底部约束设置为滚动视图。我设置它的宽度等于它的超视图,并将它的高度设置为200.到目前为止,滚动视图内部的视图非常好,我已将其约束前导,尾随,顶部和底部设置为零,相对于它的超级视图即滚动视图。我已经使它的宽度等于视图控制器视图,因为这是解决模糊宽度问题的解决方案。它解决了这个问题。现在我添加了所有按钮并将其约束设置为父视图。现在当我运行应用程序时,会出现一个类似上面添加的屏幕截图的屏幕,但是我无法滚动到最后一个元素。任何帮助都非常有用。enter image description here

2 个答案:

答案 0 :(得分:2)

这很简单。

  1. 采用scrollView(绘制左上角和右上角约束

  2. 使用 UIView ,它将像容器视图一样。(使用scrollView绘制左上角右下方约束)。

  3. 制作你的View Controller 1000px,这样你就可以让你的scrollView更大,更容易观看。你可以尽量减少它。

  4. 现在将按钮放在里面。 请记住,每个按钮都会有前导宽度,高度,并在必要时进行尾随。 宽度&高度对于scrollView非常重要,因为它的大小取决于它。

  5. 图片胜过千言万语。

    这是我的等级

    enter image description here

    这是Storyboard布局设计。白色背景基本上是containerView。

    enter image description here

    这是输出。我给了一些颜色以便更好地理解。

    enter image description here

答案 1 :(得分:0)

@IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var btnBack: UIButton!
    @IBOutlet weak var btnForward: UIButton!

let headerView = UIView()
        headerView.backgroundColor = UIColor.white

        for i in 0..<selectedRestaurant.multipleImages.count {
            let url = selectedRestaurant.multipleImages[i]

            let imgView = UIImageView()
            imgView.frame = CGRect(x: CGFloat(i) * self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: scrollView.frame.size.height)

            let task = URLSession.shared.dataTask(with: URL(string: url as! String)!, completionHandler: { (data, response, error) in

                if error == nil {
                    if data != nil {
                        imgView.contentMode = UIViewContentMode.scaleAspectFill
                        imgView.image = UIImage(data: data!)
                    }
                }



        })
                scrollView.addSubview(imgView)
scrollView.contentSize = CGSize(width: self.view.frame.size.width * CGFloat(selectedRestaurant.multipleImages.count), height: scrollView.frame.size.height)

在btn中编写代码,然后单击&lt;&lt;&lt;&lt;&lt;&lt;

let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) - 1
        print("\(index)")
        if index >= 0 {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }

在btn中编写代码,然后点击&gt;&gt;&gt;&gt;&gt;

let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) + 1
        print("\(index)")
        if index < (selectedRestaurant.multipleImages.count)  {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }