Swift下使用Xib设计界面

虽然Swift可以纯代码设计界面,不过不利用现有的可视化工具有时候有点效率低。下面是使用xib设计方法,部分代码来自网上。

(1)新建View

 

 

 

2、新建View class

 

3、DemoView.swift中

class DemoView: UIView {

// MARK:- 创建视图
class func newInstance() -> DemoView? {
let nibView = Bundle.main.loadNibNamed("DemoView", owner: nil, options: nil);

if let view = nibView?.first as? DemoView {
return view
}
return nil
}

 4、ViewController中

class LoginViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
var myView = Bundle.main.loadNibNamed("DemoView", owner: nil, options: nil)?.first as? DemoView

myView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width-50, height: self.view.frame.height-140)
myView?.center = self.view.center

if myView != nil {
self.view.addSubview(myView!)
}
}

5、调用ViewController

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window=UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor=UIColor.white
window?.makeKeyAndVisible()
window?.rootViewController=LoginViewController();
//window?.rootViewController=MainViewController()
return true
}

6、注意xib要设置

7、添加几个控件效果

8、点击两个圆环形状

9、Button上右键连线代码

 

 10、运行点击按钮看到控制台显示adfa.

 

posted @ 2018-02-21 21:06  zhaogaojian  阅读(685)  评论(0编辑  收藏  举报