MG--滚动的视觉差效果

时间:2023-03-09 02:35:38
MG--滚动的视觉差效果

#几句代码完成tableView滚动的视觉差

- 效果图 (失帧严重)
![](http://upload-images.jianshu.io/upload_images/1429890-f2c857700f043939.gif?imageMogr2/auto-orient/strip)

- ###补录一张好一点的效果图
![效果图.gif](http://upload-images.jianshu.io/upload_images/1429890-160c57b488c1c694.gif?imageMogr2/auto-orient/strip)

>- ####主要原理:
- ######1、设置UI。简单说一下,就是先往tableViewCell添加一个UIView,这个view的尺寸大小等于cell或者说等于cell.contentView;然后在往这个View添加一个UIImageView,这个imageView的约束是左右为0,水平居中,然后设置它的高度比cell大(具体数值可以根据图片的实际大小调整)因为超出父控件大小会不显示,这边设置的是400的大小。
- ######2、就是在UITableViewDelegate的代理方法`func scrollViewDidScroll(_ scrollView: UIScrollView) `方法中动态修改imageView.origin.y的值,造成一种错觉是图片滚动的视觉差。其次,要补充说明的是:我们要对cell进行处理的是出现在屏幕上的cell,并不是所有的cell,于是我们通过self.tableView.visibleCells获取所有出现屏幕上的cell,for循环遍历通过cell取出即可imageView的父视图,通过它的判断frame.origin.y通过处理,然后再将值赋值给imageView.frame.origin.y即可实现最终效果

***
- **说明**:这是在StoryBoard做的,所以在SB给view和imageView分别绑定了一个tag,以便取这两个控件,当然也可以自定义cell,然后在自定义cell中脱线出来,则不需要绑定tag,通过属性就可以取出这两个控件,更方便
- ![](http://upload-images.jianshu.io/upload_images/1429890-0ef9eecbc92ec46d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- ![辅助图](http://upload-images.jianshu.io/upload_images/1429890-e96b574a45622974.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
***

- ###代码区域

```
// ViewController.swift
// MGTableView
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// 数据源
fileprivate lazy var dataArr: [UIImage] = {
var arr: [UIImage] = [UIImage]()
for _ in 1...10 {
for i in 1...10 {
let image = UIImage(named: String(format: "%02d", i))
arr.append(image!)
}
}
return arr
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.layoutMargins = UIEdgeInsets.zero
tableView.separatorInset = UIEdgeInsets.zero
tableView.separatorStyle = .none
tableView.rowHeight = 300
}
}

// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
let imageV = cell.viewWithTag(1000) as! UIImageView
imageV.image = dataArr[indexPath.row]
return cell
}
}

// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for cell in self.tableView.visibleCells {
// 取出imageView和imageView的父视图
let imageVParentV = cell.viewWithTag(1001)
let imageV = cell.viewWithTag(1000)
let rect = imageVParentV?.convert((imageVParentV?.bounds)!, to: nil)
// var y = UIScreen.main.bounds.size.height - (rect?.origin.y)! - 560
var y = -(rect?.origin.y)!
y *= 0.2
// 判断imageView的父视图的frame.origin.y
if y>0 {
y=0
}
if y < -200 {
y = -200
}
// 重新赋值 imageView.frame.origin.y
imageV?.frame.origin.y = y
}
}
}```