33
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UIViewをコードからPreview可能にする。

Last updated at Posted at 2020-10-17

先に結論

テストとかの時にデバッガからViewを見れたら便利になるよってお話。

スクリーンショット 2020-10-17 22.17.45.png

debugQuickLookObject

Xcodeの機能として、独自クラスを見やすく表示するdebugQuickLookObject という機能がある。

この機能はBreak Pointで止めている最中にObjectのプレビューを可能にするものであり、テキストや画像、URLなんかをPreviewできる。

@objc func debugQuickLookObject() -> Any? {
    URL(string: "https://www.google.co.jp/")
}

このようにURLを返せば

スクリーンショット 2021-02-26 15.39.39.png

ページが表示される

じゃあこれでリアルタイムのUIViewを表示できたら楽しそうという考え。

実装

debugQuickLookObjectを実装する。

Swift4.0あたりから@objcをつけないと動かなくなってる。

iOS

extension UIView {
    @objc func debugQuickLookObject() -> Any? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
        drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

mac

extension NSView {
    @objc func debugQuickLookObject() -> Any? {
        guard let rep = self.bitmapImageRepForCachingDisplay(in: bounds) else { return nil }
        self.cacheDisplay(in: self.bounds, to: rep)
        
        guard let cgImage = rep.cgImage else { return nil }
        return NSImage(cgImage: cgImage, size: bounds.size)
    }
}

これでLLDBデバッガでbreakpointを貼って止めて、目のマークを押すと

スクリーンショット 2020-10-17 22.25.44.png

Viewの内容をPreviewできる。

スクリーンショット 2020-10-17 22.17.45.png

33
22
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?