★ 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
}
}