我们知道在Xcode的playground中不仅可以测试console代码,还可以测试UI代码,甚至我们可以测试SpriteKit中的场景,有兴趣的童鞋可以看我之前写的这一篇blog:
Xcode的playground中对于SpriteKit物理对象的更新为何无效
而在本篇中我们只是简单聊一聊最新的Xcode8.0 beta2(以下简称Xcode8b2)中playground对UIKit支持有了哪些改变.
首先贴出以下小段演示代码:
// 1import UIKitimport XCPlayground// 2class Responder: NSObject { func tap() { print("Button pressed") }}let responder = Responder()// 3let button = UIButton(type: .System)button.setTitle("Button", forState: .Normal)button.addTarget(responder, action: "tap", forControlEvents: .TouchUpInside)button.sizeToFit()button.center = CGPoint(x: 50, y: 25)// 4let frame = CGRect(x: 0, y: 0, width: 100, height: 50)let view = UIView(frame: frame)view.addSubview(button)XCPlaygroundPage.currentPage.liveView = view
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
导入UIKit是必须的,而导入XCPlayground是为了在UI中测试UIKit代码!不过遗憾的是以上代码并不能很好的在Xcode8b2中运行,这是因为最后一句会报错!
解决很简单,就是在playground开头再导入PlaygroundSupport库,然后将最后一句改为:
PlaygroundPage.current.liveView = view
- 1
最后别忘了打开UI测试界面:
好了我们可以在Xcode最右部分看到一个按钮显示出来,该按钮就是我们在playground中用代码即时创建出来的油 ;]
点击该按钮就会之前绑定的tap方法:
如果觉得不满意,可以随即在playground代码中立即改动UI界面然后马上看到结果,不用再建立新的Xcode UI Project了,是不是很方便呢!?
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow