Skip to content

Instantly share code, notes, and snippets.

@sooop
Created January 17, 2017 13:42
Show Gist options
  • Select an option

  • Save sooop/338e0ffab2fc75ec358f824dc30826ea to your computer and use it in GitHub Desktop.

Select an option

Save sooop/338e0ffab2fc75ec358f824dc30826ea to your computer and use it in GitHub Desktop.
탭, 누르고 있기를 통해서 탭 카운터의 숫자를 올리는 playground code.  인터페이스 빌더 없고, 뷰 컨트롤러 대신 간이 컨트롤러를 사용했다.
import UIKit
import PlaygroundSupport
class Controller: NSObject {
var button: UIButton
var label: UILabel
var view: UIView
var count: Int = 0 {
didSet {
label.text = "\(count)"
}
}
let ges = UILongPressGestureRecognizer()
var timer: Timer?
override init() {
view = UIView(frame:CGRect(x:0, y:0, width: 100, height: 150))
button = UIButton()
label = UILabel()
super.init()
prepareView()
}
/// 뷰 계층 구조를 생성하고 레이아웃을 준비함.
func prepareView() {
[button, label].forEach {
guard let v = $0 as? UIView else { return }
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
}
label.text = "tap to start"
label.textAlignment = .center
button.setTitle("+", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
let font = UIFont.systemFont(ofSize: 32)
label.font = font
let views: [String: UIView] = ["button": button, "label": label ]
var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]-(>=30)-[button]-|", options: [.alignAllCenterX], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "|-[label]-|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
view.backgroundColor = UIColor.white
button.addTarget(self, action: #selector(self.tapped(_:)), for: .touchUpInside)
ges.addTarget(self, action: #selector(self.pressed(_:)))
button.addGestureRecognizer(ges)
}
func tapped(_ sender: Any?) {
count += 1
}
func pressed(_ sender: UIGestureRecognizer?) {
guard let ges = sender as? UILongPressGestureRecognizer else { return }
switch ges.state {
case .began:
print("pressed")
let timer = Timer(timeInterval: 0.05, repeats: true, block: {[unowned self] (_) in
self.count += 1
})
RunLoop.main.add(timer, forMode: .defaultRunLoopMode)
self.timer = timer
case .cancelled, .ended:
print("ended")
self.timer?.invalidate()
self.timer = nil
default:
print(ges.state.rawValue)
break
}
}
}
let c = Controller()
PlaygroundPage.current.liveView = c.view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment