淘先锋技术网

首页 1 2 3 4 5 6 7

可以将UIScrollView理解为一块大的画布,向其中放入任意尺寸的一组视图

//
//  ViewController.swift
//  UIScrollViewTest
//
//  Created by cerf on 2021/6/20.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //进行UIScrollView的实例化
        let scrollView = UIScrollView(frame: self.view.frame)
        //将滚动视图添加到当前界面
        self.view.addSubview(scrollView)
        //创建两个内容视图
        let subView1 = UIView(frame: self.view.frame)
        subView1.backgroundColor = UIColor.red
        let subView2 = UIView(frame: CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        subView2.backgroundColor = UIColor.blue
        //将内容添加到UIScrollView视图中
        scrollView.addSubview(subView1)
        scrollView.addSubview(subView2)
        //设置UIScrollView实例的尺寸
        scrollView.contentSize = CGSize(width: self.view.frame.size.width*2, height: self.view.frame.size.height)
        //设置始终开启竖直方向的回弹效果
        scrollView.alwaysBounceVertical = true
        //设置始终开启水平方向的回弹效果
        scrollView.alwaysBounceHorizontal  = true
        //显示竖直方向的滚动条
        scrollView.showsVerticalScrollIndicator = true
        //显示水平方向的滚动条
        scrollView.showsHorizontalScrollIndicator = true
        //开启自动定位分页效果
        scrollView.isPagingEnabled = true
        // Do any additional setup after loading the view.
    }


}

设置UIScrollView的contentSize属性来控制滚动视图的可滚动范围,如果内容区域的尺寸超出了UIScrollView实例本身的尺寸大小,则当前UIScrollView实例就可以进行滑动来适应其内容区域的大小

自动定位分页是指当用户图片滑动轮播器在两个图片之间停下时,如果用户抬起手指,轮播器会自动根据图片显示出的部分尺寸大小自动定位,使轮播器完整显示某一张照片


UIScrollView的缩放操作

//
//  ViewController.swift
//  UIScrollViewTest2
//
//  Created by cerf on 2021/6/20.
//

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {
    var imageView:UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        let scrollView = UIScrollView(frame: self.view.frame)
        self.view.addSubview(scrollView)
        //设置代理
        scrollView.delegate = self
        imageView = UIImageView(image: UIImage(named: "timg"))
        imageView?.frame = self.view.frame
        scrollView.addSubview(imageView!)
        scrollView.contentSize = self.view.frame.size
        //设置缩放限度
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        // Do any additional setup after loading the view.
    }
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView!
    }


}