不使用 main storyboard的项目
在创建项目时,默认是有 main storyboard 的,如不需,步骤:
- 编辑 target,删除 General ,删除 Main Interface 里面的 "Main"。

- 删除项目中的 Main.storyboard 和 ViewController.swift 文件
- 重写 AppDelegate.swift 。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow()
self.window!.rootViewController = UIViewController()
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyWindow()
return true
}
}
使用自定义的 UIWindow
-
使用 main storyboard 的 App
lazy var window: UIWindow? = { return MyWindow() }() 不使用 main storyboard 的 App
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = MyWindow()
self.window!.rootViewController = UIViewController()
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyWindow()
return true
}
}
获取 window 的方法
-
根据 UIView 的属性直接获取
let window = self.view.window
返回值可为空,但一般情况下不会空,每个 View 肯定会在 UIWindow 上存在,如果返回空,则这个 View 不可见。
-
AppDelegate 的实例属性获取
let window = UIApplication.sharedApplication().delegate!.window!! //或者 let window1 = (UIApplication.sharedApplication().delegate as AppDelegate).window! -
根据 keyWindow 属性
let w = UIApplication.sharedApplication().keyWindow!
但是,这种方式的话,有时可能会收到影响。比如我们创建了一个临时的 UIWindow 时。
验证 UIView 的子类关系
使用isDescendantOfView方法来验证,是不是子类关系,不一定是直接子类。
let vv = UIView()
if vv.isDescendantOfView(self.view) {
print("It is subview")
}
移除所有的子类视图
let vv = UIView()
vv.subviews.forEach { (subView) in
subView.removeFromSuperview()
}
//或
vv.subviews.forEach{
$0.removeFromSuperview()
}
将子类视图显示在父类视图的 bounds 范围之外
设置视图的clipsToBounds属性。
透明度和可见性的设置
设置属性 hidden 来设置可见性,true 隐藏,false 为可见
设置属性alpha属性来设置透明度,1.0表示不透明,0.0标识透明。这个属性会影响背景色或者他上面内容的透明度也。
设置opaque。default is YES. opaque views must fill their entire bounds or the results are undefined. the active CGContext in drawRect: will not have been cleared and may have non-zeroed pixels。opaque属性提示绘制系统如何处理view。如果opaque设置为YES,绘图系统会将view看为完全不透明,这样绘图系统就可以优化一些绘制操作以提升性能。如果设置为NO,那么绘图系统结合其它内容来处理view。默认情况下,这个属性是YES。 如果屏幕是静止的,那么这个opaque属性的设置与否不是一个大问题。但是,如果view是嵌入到scroll view中的,或者是复杂动画的一部分,不将设置这个属性的话,肯定会影响程序的性能!可以通过模拟器的Debug\Color Blended Layers选项来查看哪些view没有设置为不透明。为了程序的性能,尽可能的将view设置为不透明!