Swift - UIScrollView

Posted baidaye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
    }
   
}

 

以上是关于Swift - UIScrollView的主要内容,如果未能解决你的问题,请参考以下文章

Swift 向 UIScrollView 子视图添加约束

Swift UIScrollview 双击 uitbutton 缩放

Swift:按钮在 UIScrollView 中不起作用

Swift - 以编程方式将 UIScrollView 宽度设置为 100%

在 UIScrollView Swift3 中加载 UIViewController

swift开发之 -- 自动轮播图(UIScrollView+UIPageControl+Timer)