Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 7, 2016 01:38
Show Gist options
  • Save KentarouKanno/631b20ae9c00f2e14dc0 to your computer and use it in GitHub Desktop.
Save KentarouKanno/631b20ae9c00f2e14dc0 to your computer and use it in GitHub Desktop.

extension

使うと手放せなくなるSwift Extension集

★ Viewの幅と高さを取得する

print(self.view.width)
print(self.view.height)


extension UIView {
    var width: CGFloat {
        return self.frame.size.width
    }
    
    var height: CGFloat {
        return self.frame.size.height
    }
}

★ ファイル名を指定して、ファイルパスを取得

// DocumentDirectory Generate Path
extension String {

    // ~/Library/Documents
    func generateDocumentPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/\(self)"
    }

    // ~/Library/Caches
    func generateCachesPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! + "/\(self)"
    }

    // ~/tmp
    func generateTmpPath() -> String {
        return NSTemporaryDirectory() + "/\(self)"
    }
}

// Usage

let path = "test.plist".generateDocumentPath()

let intArray: NSArray = [1, 2, 3, 4, 5]
let isWriteSuccess = intArray.writeToFile(path, atomically: true)

★ 画面のスクリーンショットをUIImageで取得する

// 対象のViewを指定してスクリーンショットを取得する

extension UIView {
    func snapShot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1)
        drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

// Windowから(Keyboard, AlertControllerも映る)

extension UIView {
    func snapShotFromWindow() -> UIImage {
        let window = UIApplication.sharedApplication().keyWindow
        UIGraphicsBeginImageContextWithOptions(window!.bounds.size, false, 1)
        let context = UIGraphicsGetCurrentContext()
        for window in UIApplication.sharedApplication().windows {
            window.layer.renderInContext(context!)
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment