作者:淡泊宁静1110 | 来源:互联网 | 2023-09-25 15:13
1,当图片尺寸超过屏幕时,使用UIScrollView可以实现滚动条视图,即手指触摸滚动屏幕方便浏览整个页面。
1
2
3
4
5
6
|
var
scrollView=
UIScrollView
()
scrollView.frame=
self
.view.bounds
var
imageView=
UIImageView
(image:
UIImage
(named:
"bigpic"
))
scrollView.cOntentSize=imageView.bounds.size;
scrollView.addSubview(imageView);
self
.view.addSubview(scrollView)
|
2,获取滚动视图移动的x,y坐标
通过scrollView.contentOffset.x与scrollView.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
var
imageView=
UIImageView
(image:
UIImage
(named:
"ii"
))
scrollView.cOntentSize=imageView.bounds.size;
scrollView.addSubview(imageView);
self
.view.addSubview(scrollView)
}
func
scrollViewDidScroll(scrollView:
UIScrollView
) {
println
(
"x:\(scrollView.contentOffset.x) y:\(scrollView.contentOffset.y)"
)
}
override
func
didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
|
3,手势放大缩小
要实现放大缩小功能,需要指定UIScrollView的允许缩放最大比例和最小比例(默认都是是1.0)。
同时delegate属性指定一个委托类,委托类要继承UIScrollViewDelegate协议,并在委托类中实现viewForZoomingInScrollView方法。
(注:在模拟器中测试,需要按住option键再拖动内容)
1
2
3
4
5
6
7
8
9
10
11
12
|
scrollView.minimumZoomScale=0.1
scrollView.maximumZoomScale=3
scrollView.delegate=
self
func
viewForZoomingInScrollView( scrollView:
UIScrollView
!) ->
UIView
!{
for
subview :
AnyObject
in
scrollView.subviews {
if
subview.isKindOfClass(
UIImageView
) {
return
subview
as
UIView
}
}
return
nil
}
|