UIScrollView 滾動視圖
- 首先初始化一個UIScrollView冯事,并且設置好它的x膊存,y以及寬和高遥倦,
- 這里我們將他的寬高設置成我們模擬器的大小。
let scr = UIScrollView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
//添加背景顏色
scr.backgroundColor = UIColor.red
- 然后我們設置碉考,滑動區(qū)域的大小塌计,這里我們會添加三張圖片,所以給模擬器的寬*3.高依然是模擬器的高
//設置滑動內(nèi)容區(qū)域的大小
scr .contentSize = CGSize(width: self.view.frame.size.width * 3, height: self.view.frame.size.height)
//添加到父視圖上
self.view.addSubview(scr)
//是否可以整頁翻動
scr.isPagingEnabled = true
//觸壁反彈
scr.bounces = false
//取消滑動條
scr.showsHorizontalScrollIndicator = false
scr.indicatorStyle = .black
//是否關閉拖拽
scr.isScrollEnabled = false
- 這里我們實現(xiàn)視圖的放大侯谁,縮小锌仅。
- 獲取偏移量
//加載圖片
self.loadImage(scr: scr)
//設置代理
scr.delegate = self
//縮放的值
scr.minimumZoomScale = 0.2
scr.maximumZoomScale = 2
//設置偏移量
scr.contentOffset = CGPoint(x: self.view.frame.size.width, y: 0)
}
//縮放要實現(xiàn)的方法(返回要縮放的控件)
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
for view in scrollView.subviews {
if view is UIImageView {
return view
}
}
return nil
}
//代理方法
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("任何偏移都會執(zhí)行")
//獲取偏移量
print(scrollView.contentOffset)
}
//開始拖拽
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("開始拖拽")
}
//結(jié)束拖拽
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
print("結(jié)束拖拽")
}
//開始減速
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
print("開始減速")
}
//結(jié)束減速
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
print("結(jié)束減速")
}
//加載圖片的方法
func loadImage(scr:UIScrollView) {
let imageV1 = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
imageV1.image = UIImage(named:"7.jpg")
scr.addSubview(imageV1)
let imageV2 = UIImageView(frame: CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
imageV2.image = UIImage(named:"8.jpg")
scr.addSubview(imageV2)
let imageV3 = UIImageView(frame: CGRect(x: self.view.frame.size.width * 2, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
imageV3.image = UIImage(named:"10.jpg")
scr.addSubview(imageV3)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者