Swift - UIScrollView

1、UIScrollView滚动视图的用法

import UIKit
class ViewController: UIViewController,UIScrollViewDelegate{
    
    var scrollView:UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView = UIScrollView()
        scrollView.frame = self.view.bounds
        scrollView.delegate = self
        let imageView = UIImageView(image: UIImage(named: "welcome_page"))
        scrollView.contentSize = imageView.bounds.size
        scrollView.addSubview(imageView)
        scrollView.minimumZoomScale = 0.1//最小比例
        scrollView.maximumZoomScale = 3 //最大比例
        self.view.addSubview(scrollView)
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("x:\(scrollView.contentOffset.x) y:\(scrollView.contentOffset.y)")
    }
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        for subview:AnyObject in scrollView.subviews{
            if subview.isKind(of: UIImageView.self){
                return subview as? UIView
            }
        }
        return nil
    }
}

 2、实现页面滚动切换

import UIKit
class ViewController: UIViewController{
    
    let numofPages = 3
    let pageWidth = (NSInteger)(UIScreen.main.bounds.width)
    let pageHeight = (NSInteger)(UIScreen.main.bounds.height)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let scrollView = UIScrollView()
        scrollView.frame = self.view.bounds
        scrollView.contentSize = CGSize(width: pageWidth*numofPages, height: pageHeight)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.scrollsToTop = false
        scrollView.bounces = false
        
        //添加子页面
        for i in 0..<numofPages{
            let view = UIView()
            view.frame = CGRect(x: pageWidth*i, y: 0, width: pageWidth, height: pageHeight)
            view.backgroundColor = UIColor(red: CGFloat(arc4random()%256)/255.0, green: CGFloat(arc4random()%256)/255.0, blue: CGFloat(arc4random()%256)/255.0, alpha: 1.0)
            scrollView.addSubview(view)
        }
        self.view.addSubview(scrollView)
    }
   
}

 

posted @ 2018-06-20 16:17  小白姐  阅读(300)  评论(0编辑  收藏  举报