Swift UI - 滚动视图(UIScrollView)

注:代码已升级至Swift4

基本使用

当内容尺寸超过屏幕时,使用UIScrollView可以实现滚动条视图,即手指触摸滚动屏幕方便浏览整个页面。

1
2
3
4
5
6
let scrollView = UIScrollView()
scrollView.frame = self.view.bounds
let imageView = UIImageView(image:UIImage(named:"bigpic"))
scrollView.contentSize = imageView.bounds.size
scrollView.addSubview(imageView)
self.view.addSubview(scrollView)

获取滚动视图移动的x,y坐标

通过scrollView.contentOffset.xscrollView.contentOffset.y,我们可以取到移动的偏移位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

var scrollView:UIScrollView!

override func viewDidLoad() {
super.viewDidLoad()

scrollView = UIScrollView()
//设置代理
scrollView.delegate = self
scrollView.frame = self.view.bounds
let imageView = UIImageView(image:UIImage(named:"bigpic.jpg"))
scrollView.contentSize = imageView.bounds.size
scrollView.addSubview(imageView)
self.view.addSubview(scrollView)
}

//视图滚动中一直触发
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("x:\(scrollView.contentOffset.x) y:\(scrollView.contentOffset.y)")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

手势放大缩小

要实现放大缩小功能,需要指定UIScrollView的允许缩放最大比例和最小比例(默认都是是1.0)。同时delegate属性指定一个委托类,委托类要继承UIScrollViewDelegate协议,并在委托类中实现viewForZooming方法。

注:在模拟器中测试,需要按住option键再拖动内容

1
2
3
4
5
6
7
8
9
10
11
12
scrollView.minimumZoomScale = 0.1  //最小比例
scrollView.maximumZoomScale = 3 //最大比例
scrollView.delegate = self

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
for subview : AnyObject in scrollView.subviews {
if subview.isKind(of: UIImageView.self) {
return subview as? UIView
}
}
return nil
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :