当在真实设备上运行时,snapshotView(afterScreenUpdates:true)返回空视图

时间:2019-07-01 19:46:49

标签: ios swift iphone ios-simulator

在模拟器(iPhone 7和iPhone XR)中运行时,snapshotView(afterScreenUpdates:true)效果很好,符合预期。但是,当我在物理iPhone 7设备上对其进行测试时,它会返回空白视图,但框架正确。

我需要UIView对象,并且无法使用UIImage来解决类似问题的以前的许多建议。

let snappedView = view.snapshotView(afterScreenUpdates: true)

2 个答案:

答案 0 :(得分:0)

此扩展程序可能对您有用:

public extension UIView {

    public func snapshotImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage =         UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }

    public func snapshotView() -> UIView? {
        if let snapshotImage = snapshotImage() {
            return UIImageView(image: snapshotImage)
        } else {
            return nil
        }
    }
}

答案 1 :(得分:0)

如果需要,您可以使用此功能为iPhone屏幕截图:

func takeSnapshot() {
  UIGraphicsBeginImageContext(view.frame.size)
  view.layer.render(in: UIGraphicsGetCurrentContext()!)
  let img = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
}