从 iOS 7 开始,苹果提供了监听用户截屏操作的通知:
@available(iOS 7.0, *)
public static let UIApplicationUserDidTakeScreenshot: NSNotification.Name
我们可以使用这个通知来做例如:截屏弹出分享窗口的功能。
// 监听通知
NotificationCenter.default.addObserver(self, selector: #selector(screenShot), name: Notification.Name.UIApplicationUserDidTakeScreenshot, object: nil)
func screenShot() {
let image = fullScreenShot(tableView)
let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
}
// 有时,需要截取 tableView 或 scrollView 的全部内容,使用以下方法:
/// 长截屏
func fullScreenShot(_ scrollView: UIScrollView) -> UIImage {
// 记录当前 scrollView 的"偏移量"和"坐标"
let savedContentOffset = scrollView.contentOffset
let savedScrollViewFrame = scrollView.frame
scrollView.contentOffset = .zero
scrollView.frame = CGRect(origin: .zero, size: scrollView.contentSize)
UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, true, UIScreen.main.scale)
scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
// 重置
scrollView.contentOffset = savedContentOffset
scrollView.frame = savedScrollViewFrame
UIGraphicsEndImageContext()
return image
}