UIScrollView 滚动视图

UIScrollView 滚动视图

  • 首先初始化一个UIScrollView,并且设置好它的x,y以及宽和高,
  • 这里我们将他的宽高设置成我们模拟器的大小。
let scr = UIScrollView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
//添加背景颜色   
scr.backgroundColor = UIColor.red
  • 然后我们设置,滑动区域的大小,这里我们会添加三张图片,所以给模拟器的宽*3.高依然是模拟器的高
//设置滑动内容区域的大小
scr .contentSize = CGSize(width: self.view.frame.size.width * 3, height: self.view.frame.size.height)
//添加到父视图上
self.view.addSubview(scr)
  • 下面是一些属性
//是否可以整页翻动
scr.isPagingEnabled = true
//触壁反弹
scr.bounces = false
//取消滑动条
scr.showsHorizontalScrollIndicator = false
scr.indicatorStyle = .black
//是否关闭拖拽
scr.isScrollEnabled = false
  • 这里我们实现视图的放大,缩小。
  • 获取偏移量
//加载图片
self.loadImage(scr: scr)
        
//设置代理
scr.delegate = self
//缩放的值
scr.minimumZoomScale = 0.2
scr.maximumZoomScale = 2
        
//设置偏移量
scr.contentOffset = CGPoint(x: self.view.frame.size.width, y: 0)
        
    }
    //缩放要实现的方法(返回要缩放的控件)
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        for view in scrollView.subviews {
            if view is UIImageView {
                return view
            }
        }
        return nil
    }
    
    //代理方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("任何偏移都会执行")
        //获取偏移量
        print(scrollView.contentOffset)
    }
    //开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("开始拖拽")
        
    }
    //结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print("结束拖拽")
    }
    
    //开始减速
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        print("开始减速")
    }
    //结束减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("结束减速")
    }
    //加载图片的方法
    func loadImage(scr:UIScrollView) {
        let imageV1 = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageV1.image = UIImage(named:"7.jpg")
        scr.addSubview(imageV1)
        
        let imageV2 = UIImageView(frame: CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageV2.image = UIImage(named:"8.jpg")
        scr.addSubview(imageV2)
        
         let imageV3 = UIImageView(frame: CGRect(x: self.view.frame.size.width * 2, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageV3.image = UIImage(named:"10.jpg")
        scr.addSubview(imageV3)

你可能感兴趣的:(UIScrollView 滚动视图)