什么是防抖,为什么要防抖?
比如我们在文档在线编辑中修改文档内容,总不能打一个字就发送一次更新请求吧,用户疯狂点击一个按钮,总不能一直触发按钮的逻辑吧。防抖被用于避免频繁触发的事件。
Swift实现防抖代码:
Swift
import Foundation
class Debouncer {
var delay: TimeInterval
var timer: Timer?
var closure: (() -> Void)?
init(delay: TimeInterval) {
self.delay = delay
}
func debounce(closure: @escaping () -> Void) {
self.closure = closure
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(fire), userInfo: nil, repeats: false)
}
@objc func fire() {
closure?()
}
}
let debouncer = Debouncer(delay: 0.5)
func action() {
print("Debounced action executed")
}
debouncer.debounce {
action()
}
debouncer.debounce {
action()
}
什么是图片预加载,为什么要预加载,为什么要拼接?
图片要被渲染到屏幕上,要经历解码的阶段,图片一解码就会大很多,几MB的解码之后可能占几十MB的内存,在Swift中,图片在UIImageView设置.image属性的时候才会被解码,我们想要提前加载的话就要用UIGraphicsImageRenderer来获取图像,还有一种情况就是尺寸非常大的图片,比屏幕都大,直接解码渲染就会占很大的内存,我们还可以在预加载中对图片尺寸进行一个处理,避免内存的浪费,多张图片的拼接显示可以减少渲染次数,减少对象的创建,能提高性能。
下面是Swift代码:
Swift
import UIKit
class ViewController: UIViewController {
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: self.view.frame)
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
let imageUrls = [
URL(string: "https://images.pexels.com/photos/356830/pexels-photo-356830.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2")!,
URL(string: "https://images.pexels.com/photos/356830/pexels-photo-356830.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2")!
]
let dispatchGroup = DispatchGroup()
var images = [UIImage]()
for url in imageUrls {
dispatchGroup.enter()
URLSession.shared.dataTask(with: url) { data, _, error in
defer { dispatchGroup.leave() }
if let data = data, let image = UIImage(data: data) {
images.append(image)
}
}.resume()
}
dispatchGroup.notify(queue: .main) {
if let combinedImage = self.combineImages(images: images) {
self.imageView.image = combinedImage
self.view.addSubview(self.imageView)
}
}
}
func combineImages(images: [UIImage]) -> UIImage? {
let renderer = UIGraphicsImageRenderer(size: self.view.frame.size)
let combinedImage = renderer.image { context in
var currentX = 0.0
for image in images {
image.draw(at: CGPoint(x: currentX, y: 0))
currentX += image.size.width
}
}
return combinedImage
}
}
本文的内容就到这里啦,喜欢博主的可以点点关注。