playground是用于swift学习和交互简化的工具,无需编码知识即可学习,然而你需要懂得这个工具的几个地方
- 控制台程序
- UI程序
- 访问source文件
控制台应用
打开Xcode创建PlayGround工程
var str = "ttt"
print(str)
控制台效果图
在右侧即可显示结果
UI程序
- import PlaygroundSupport
- AssistentEditor
let containerView = UIView(frame:CGRect(x:0.0, y:0.0, width:375.0, height:667.0))
containerView.backgroundColor = UIColor.white
let contentView = UIView(frame:CGRect(x:0, y:0, width:100, height:100))
contentView.backgroundColor = UIColor.yellow
containerView.addSubview(contentView)
contentView.center = containerView.center
UIView.animate(withDuration:0.2, animations: {
contentView.transform = CGAffineTransform(scaleX:0.8, y:0.8)
}) { (result) in
UIView.animate(withDuration:1, animations: {
contentView.transform=CGAffineTransform(scaleX:4, y:4)
contentView.alpha=0
})
}
PlaygroundPage.current.liveView = containerView
UI效果图.jpg
访问source文件
- 打开Navigator
- 在Sources文件夹里面写入文件
- swift文件内的class需要为public包括暴露的方法,因为这里会当做你不同模块处理
//只需要在playground里面加入一句话
PlaygroundPage.current.liveView=ButtonViewController()
//sources 下的swift文件
import Foundation
import UIKit
public class ButtonViewController : UIViewController {
var counter = 0
var label : UILabel!
var button : UIButton!
var starButton : UIButton!
public override func loadView() {
// UI
let view = UIView()
view.backgroundColor = .white
label = UILabel()
button = UIButton(type: .system)
button.setTitle("Increment", for: .normal)
button.tintColor = .red
button.addTarget(self, action: #selector(updateView), for: .touchUpInside)
starButton = UIButton(type: .system)
starButton.setTitle("Star",for:.normal)
starButton.addTarget(self, action: #selector(toggleStarred), for: .touchUpInside)
view.addSubview(label)
view.addSubview(button)
view.addSubview(starButton)
// Layout
label.translatesAutoresizingMaskIntoConstraints = false
button.translatesAutoresizingMaskIntoConstraints = false
starButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
button.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: 20),
button.firstBaselineAnchor.constraint(equalTo: label.firstBaselineAnchor),
starButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
starButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
])
self.view = view
self.starred = false
updateView()
}
@objc func updateView() {
counter += 1
label.text = "Counter: \(counter)"
}
@objc func toggleStarred() {
self.starred = !self.starred
}
var starred = false {
didSet {
starButton.tintColor = starred ? .orange : .gray
}
}
}
popo_2017-12-14 20-33-16.jpg
网友评论