swift初窥--playground

Playground是随着Swift在WWDC2014推出的,从字面意思来理解,"playground"就是操场,游乐场的意思。在Swift中,这个"游乐场",可以一边写代码,一边预览效果,实现“所见即所写”,这给程序员带来的方便是不言而喻的,通过两张图来对比:




从6步,简化成两步,是不是很酷?除了酷,Playground是可以应用在实际开发中的,在两个地方使用效果很好:用来快速预览界面控件效果,用来调试复杂算法。

现在来点干货,

预览imageview

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. let imageNames = [NSImageNameUser,NSImageNameUserAccounts,NSImageNameUserGroup]  
  2. let images = imageNames.map{NSImage(named:$0)};  
  3. images  
  4. let image = images[0]  
  5. let imageView = NSImageView(frame:NSRect(x: 0,y: 0,width: 512,height: 512))  
  6. imageView.image = image  
  7. imageView.imageScaling = .ImageScaleProportionallyUpOrDown  

预览tableview

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2. var str = "Hello, playground"  
  3.   
  4. class DataSource: NSObject,UITableViewDataSource{  
  5.       
  6.       
  7.     func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{  
  8.         return 4  
  9.     }  
  10.     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{  
  11.         let row = indexPath.row  
  12.         let style = UITableViewCellStyle.fromRaw(row)  
  13.         let cell = UITableViewCell(style: style!,reuseIdentifier: nil)  
  14.         //let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)  
  15.           
  16.         cell.textLabel.text = "Text1"  
  17.       
  18.         if let detailTextLabel = cell.detailTextLabel{  
  19.             detailTextLabel.text = "Detail Text"  
  20.         }  
  21.         return cell  
  22.     }  
  23.       
  24. }  
  25.   
  26. let ds = DataSource()  
  27. let tableView = UITableView(frame: CGRect(x:0, y:0, width: 320,height: 240), style: .Plain)  
  28. //let tableView = UITableView(frame: CGRectMake(0.0,0.0,320.0,240.0), style: .Plain)  
  29. tableView.dataSource = ds  
  30. tableView.reloadData()  


Playground支持的数据类型:


Playground的局限:

1 无法直接将playground文件直接用到工程中,但可拷贝粘贴code进工程。



Q&A

1 导入UIKit失败

在playground中输入

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
出现"No such module UIKit"错误,解决方法是,将platform 设为iOS(默认是OS X)

打开File Inspector,如下图设置



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值