您的位置:首页 > 移动开发 > Swift

Swift初窥----Playground

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





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

现在来点干货,

预览imageview

let imageNames = [NSImageNameUser,NSImageNameUserAccounts,NSImageNameUserGroup]
let images = imageNames.map{NSImage(named:$0)};
images
let image = images[0]
let imageView = NSImageView(frame:NSRect(x: 0,y: 0,width: 512,height: 512))
imageView.image = image
imageView.imageScaling = .ImageScaleProportionallyUpOrDown


预览tableview

import UIKit
var str = "Hello, playground"

class DataSource: NSObject,UITableViewDataSource{
    
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        return 4
    }
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        let row = indexPath.row
        let style = UITableViewCellStyle.fromRaw(row)
        let cell = UITableViewCell(style: style!,reuseIdentifier: nil)
        //let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
        
        cell.textLabel.text = "Text1"
    
        if let detailTextLabel = cell.detailTextLabel{
            detailTextLabel.text = "Detail Text"
        }
        return cell
    }
    
}

let ds = DataSource()
let tableView = UITableView(frame: CGRect(x:0, y:0, width: 320,height: 240), style: .Plain)
//let tableView = UITableView(frame: CGRectMake(0.0,0.0,320.0,240.0), style: .Plain)
tableView.dataSource = ds
tableView.reloadData()


Playground支持的数据类型:



Playground的局限:

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

Q&A

1 导入UIKit失败

在playground中输入

import UIKit
出现"No such module UIKit"错误,解决方法是,将platform 设为iOS(默认是OS X)

打开File Inspector,如下图设置

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: