微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift3的playground中对UI直接测试支持的改变

我们知道在Xcode的playground中不仅可以测试console代码,还可以测试UI代码,甚至我们可以测试SpriteKit中的场景,有兴趣的童鞋可以看我之前写的这一篇blog:

Xcode的playground中对于SpriteKit物理对象的更新为何无效

而在本篇中我们只是简单聊一聊最新的Xcode8.0 beta2(以下简称Xcode8b2)中playground对UIKit支持有了哪些改变.

首先贴出以下小段演示代码:

// 1
import UIKit
import XCPlayground

// 2
class Responder: NSObject {

  func tap() {
    print("Button pressed")
  }
}
let responder = Responder()

// 3
let 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)

// 4
let frame = CGRect(x: 0,y: 0,width: 100,height: 50)
let view = UIView(frame: frame)
view.addSubview(button)
XCPlaygroundPage.currentPage.liveView = view

导入UIKit是必须的,而导入XCPlayground是为了在UI中测试UIKit代码!不过遗憾的是以上代码并不能很好的在Xcode8b2中运行,这是因为最后一句会报错!

解决很简单,就是在playground开头再导入PlaygroundSupport库,然后将最后一句改为:

PlaygroundPage.current.liveView = view

最后别忘了打开UI测试界面:

好了我们可以在Xcode最右部分看到一个按钮显示出来,该按钮就是我们在playground中用代码即时创建出来的油 ;]

点击该按钮就会之前绑定的tap方法:

如果觉得不满意,可以随即在playground代码中立即改动UI界面然后马上看到结果,不用再建立新的Xcode UI Project了,是不是很方便呢!?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐