swift 带有Swift闭包的预定NSTimer

带有Swift闭包的预定NSTimer

NSTimer+Closure.swift
extension NSTimer {
    /**
    Creates and schedules a one-time `NSTimer` instance.
    
    - Parameters:
        - delay: The delay before execution.
        - handler: A closure to execute after `delay`.
    
    - Returns: The newly-created `NSTimer` instance.
    */
    class func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
    
    /**
    Creates and schedules a repeating `NSTimer` instance.
    
    - Parameters:
        - repeatInterval: The interval (in seconds) between each execution of
          `handler`. Note that individual calls may be delayed; subsequent calls
          to `handler` will be based on the time the timer was created.
        - handler: A closure to execute at each `repeatInterval`.
    
    - Returns: The newly-created `NSTimer` instance.
    */
    class func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = interval + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
}

// Usage:
var count = 0
NSTimer.schedule(repeatInterval: 1) { timer in
    print(++count)
    if count >= 10 {
        timer.invalidate()
    }
}

NSTimer.schedule(delay: 5) { timer in
    print("5 seconds")
}

swift 表格导航控制器

表格导航控制器

FormNavigationController.swift
//
//  Copyright © 2014 Yuri Kotov
//

import UIKit

@objc
protocol FormNavigation {
    var nextField: UIResponder? {get}
}

class FormNavigationController: NSObject {
    let action: Selector = "textFieldDidReturn:"

    @IBOutlet
    var fields: [UITextField] = [] {
        willSet { unsubscribe(fields) }
        didSet { subscribe(fields) }
    }

    func subscribe(fields: [UITextField]) {
        fields.map { $0.addTarget(self, action: self.action, forControlEvents: UIControlEvents.EditingDidEndOnExit) }
    }

    func unsubscribe(fields: [UITextField]) {
        fields.map { $0.removeTarget(self, action: self.action, forControlEvents: UIControlEvents.EditingDidEndOnExit) }
    }

    func textFieldDidReturn(sender: UITextField) {
        if let field = sender as? FormNavigation {
            field.nextField?.becomeFirstResponder()
        } else if var index = find(fields, sender) {
            if ++index < fields.count {
                fields[index].becomeFirstResponder()
            }
        }
    }

    deinit {
        unsubscribe(fields)
    }
}

swift 在Swift中使用日期,日历。

在Swift中使用日期,日历。

working_with_dates.swift
// Playground - noun: a place where people can play

import UIKit

// Setup the calendar object
let calendar = NSCalendar.currentCalendar()

// Set up date object
let date = NSDate()

// Create an NSDate for the first and last day of the month
//let components = calendar.components(NSCalendarUnit.CalendarUnitYear |
//                                     NSCalendarUnit.CalendarUnitMonth |
//                                     NSCalendarUnit.WeekdayCalendarUnit |
//                                     NSCalendarUnit.WeekCalendarUnit |
//                                     NSCalendarUnit.CalendarUnitDay,
//                                     fromDate: date)

// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)


components.month

// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!

components.month  += 1
components.day     = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!

var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
                NSCalendarUnit.WeekdayCalendarUnit     |
                NSCalendarUnit.CalendarUnitDay

let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents  = calendar.components(unitFlags, fromDate: lastDateOfMonth)

// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek  = lastDateComponents.weekOfMonth

let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend  = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7

let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate:   NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!

Array(map(0..<42) {
    calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
})

"\(components.year)"


var dateString = "2014-10-3" // change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"

var someDate = dateFormatter.dateFromString(dateString)
println(someDate)

swift 的UIViewのカテゴリ.Flashライクにポジションアクセス

的UIViewのカテゴリ.Flashライクにポジションアクセス

flashlike.swift
extension UIView
{
    var anchorPoint:CGPoint {
        get {
            return self.layer.anchorPoint
        }
        set {
            self.layer.anchorPoint = newValue
        }
    }
    
    var x:CGFloat {
        get {
            return self.layer.position.x;
        }
        set {
            self.layer.position.x = newValue
        }
    }
    
    var y:CGFloat {
        get {
            return self.layer.position.y;
        }
        set {
            self.layer.position.y = newValue
        }
    }
    
    
    var position:CGPoint {
        get {
            return self.layer.position;
        }
        set {
           self.layer.position = newValue;
        }
    }
    
    var angle:CGFloat {

        get{
            return 0;
        }
        set {
            var rad = M_PI/180
            var v = newValue * CGFloat(rad)
            self.transform = CGAffineTransformMakeRotation(v)
        }
    }
}

swift Helloworld Swift

Helloworld Swift

uilabel.swift
//
//  ViewController.swift
//  helloworld-swift
//
//  Created by Shunsuke Ohba on 2014/10/04.
//  Copyright (c) 2014年 Shunsuke Ohba. All rights reserved.
//

import UIKit

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // 全体サイズ 第1第2引数を0にすると、中心が座標となるこの場合(150,200)
        let myLabel:UILabel = UILabel(frame:CGRectMake(0, 0, 300, 400))
        // layerの座標は150, 200を指す
        // デフォルトでこのような処理になることを肝に命じておこう
        print(myLabel.layer.position)
        myLabel.backgroundColor = UIColor.orangeColor()
        myLabel.text = "Hello world Swift"
        myLabel.layer.masksToBounds = true
        myLabel.textColor = UIColor.blackColor()
//        myLabel.x = 20
//        myLabel.y = 10
//        myLabel.position = CGPointMake (20, 10);

        myLabel.layer.position = CGPointMake(0, 0)
        myLabel.layer.anchorPoint = CGPointMake (0, 0)
        myLabel.angle = 30
//        myLabel.xx = 0
        self.view.addSubview(myLabel);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension UIView
{
    var anchorPoint:CGPoint {
        get {
            return self.layer.anchorPoint
        }
        set {
            self.layer.anchorPoint = newValue
        }
    }
    
    var x:CGFloat {
        get {
            return self.layer.position.x;
        }
        set {
            self.layer.position.x = newValue
        }
    }
    
    var y:CGFloat {
        get {
            return self.layer.position.y;
        }
        set {
            self.layer.position.y = newValue
        }
    }
    
    
    var position:CGPoint {
        get {
            return self.layer.position;
        }
        set {
           self.layer.position = newValue;
        }
    }
    
    var angle:CGFloat {

        get{
            return 0;
        }
        set {
            var rad = M_PI/180
            var v = newValue * CGFloat(rad)
            self.transform = CGAffineTransformMakeRotation(v)
        }
    }
}

swift Swift 1.核心语法

Swift 1.核心语法

whileLoopStatement.swift
// Creating while loops in Swift
/*
while condition {
    // do something
}

do{
    // do something
} while condition



*/
switchStatement.swift
// Switch STATEMENT
let windSpeed = 5;
switch windSpeed {
    
case 0:
    println("It couldn't be ");
    // in the case it's 0, do this
    
case 1:
    println("There's harldy a breeze.");
    // in the case it's 1, do this
    // (etc)
    
case 12 :
    println("Hurricane! Batten down the hatches!")
    // in the case it's 12, do this
    
// Swift - using ranges
case 0...3:
    println("it's vary calm")

case 4...6:
    println("A little windy");
    
default:
    //all other value
    break // to explicitly end this otherwise empty case
}
rangeOperator.swift
/* 
1. ... closed range operator
    0...100 
    36...99
    0...someVariable


2. ..< half-open range operator
    0..<100
    36..<99
    0..<someArray.count

the only difference is that the half-range operator does not include the number at the right side

*/
ifStatement.swift
// THE if STATEMENT
var myVar_ifStatement = 1;
if myVar_ifStatement > 500 {
    //do somethings
}else if myVar_ifStatement < 500{
    // do somethings
}
forLoopsStatement.swift
//Creating for loops in Swift
//initializer ; condition; increment
for var i=0; i<100; i++ {
    //
}

// Creating for-in loops in Swift

/*
for each-item in some-collection {
    use each-item
}
*/

var total = 0
for index in 1...100{ //1...100 closed range operator
    total = total + index
}

println("The total is \(total)")
forInLoopStatement.swift
// Using for-in loops with Strings
var name = "Bob";
for eachChar in name{
    println(eachChar);
}
defineFunc.swift
// Defining Functions
// !!! 
// in Swift, by default, an input parameter is constant, not variable
// for example

func paramsAreConstant( age: Int){
    // age = age + 1 not allowed, because the age is constant
}

func paramsAreConstant_var(var age: Int){
    // age = age + 1 now allowed, because the age is constant
}

func myFunction( name: String, age: Int){
    println("This is a simple funciton.");
}

// to call
//myFunction()


// Functions that return value
func myFunciton_return() -> String{
    return "hello";
}



// Using default parameter values
func myFunction_withDefaultValue(name : String = "John Doe"){
    println("hello, \(name)");
}

// to call
myFunction_withDefaultValue() // Okay output "hello, John Doe"
// !!! myFunction_withDefaultValue() // ERROR - this will not work 
myFunction_withDefaultValue(name : "Jane") // Okay output "hello, Jane"

// Using named parameters

func add(a:Int = 10, b: Int = 50){
    println("The result is \(a+b)");
}

// add(99) ERROR, compiler error
add(a: 99);
add(b: 200);
add(a:99, b:200);





StringBasic.swift
var str = "Hello, playground";

var highScore:Int = 1000;
highScore = highScore + 100;

for i in 0..<100 {
    highScore = highScore + i;
}

var firstName:String = "Chip";
var isActive:Bool = true;

var myVariable: Int;

let daysInWeek = 7;

println("this is a print statement!");


//String Interpolation in Swift
let city = "Shanghai";
var day = "Saturday";
var temp = 75;
println("The hign for \(city) on \(day) is \(temp) degrees!");


// String Interpolation with Expression
var quantity = 17;
var unitPrice = 349;
println("The amount is \(quantity * unitPrice)");

//Expression using different TYPES
//Swift doesn't implicitely convert VALUES
var quantity_int: Int = 17; //Int
var unitPrice_double: Double = 349.54; // Double

//to convert, use Double(), Int(), String() etc
println("The amount is \(Double(quantity_int) * unitPrice_double)");

swift 在Swift中使用C#启发事件处理

在Swift中使用C#启发事件处理

ViewController.swift
class ViewController: UIViewController {

    @IBOutlet
    weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.TouchUpInside += action

        button.TouchUpInside += {sender in
            println("closure: \(sender)")
        }
    }

    func action(sender: AnyObject) {
        println("method: = \(sender)")
    }
}
UIControl+Event.swift
extension UIControl {
    struct ControlEvents {
        static let TouchUpInside = "TouchUpInside"
    }

    var TouchUpInside: Event {
        return objc_getAssociatedObject(self, ControlEvents.TouchUpInside) as Event! ?? {
            let event = Event()
            self.addTarget(event, action: "invoke:", forControlEvents:UIControlEvents.TouchUpInside)
            objc_setAssociatedObject(self, ControlEvents.TouchUpInside, event, UInt(OBJC_ASSOCIATION_RETAIN))
            return event
        }()
    }
}
Event.swift
typealias EventHandler = (AnyObject) -> Void

class Event {
    var handlers: [EventHandler] = []

    func subscribe(handler: EventHandler) {
        handlers.append(handler)
    }

    dynamic func invoke(sender: AnyObject) {
        handlers.map({$0(sender)})
    }
}

func +=(event: Event, handler: EventHandler) {
    event.subscribe(handler)
}

swift Functional.swift游乐场

Functional.swift游乐场

Functional.swift
struct fn {

  static func get<A, B>(property: A) -> [A: B] -> B? {
    return { obj in self.get(property, obj) }
  }

  static func get<A, B>(property: A, _ obj: [A: B]) -> B? {
    return obj[property]
  }


  static func map<A, B>(fn: A -> B) -> [A] -> [B] {
    return { list in self.map(fn, list) }
  }

  static func map<A, B>(fn: A -> B, _ list: [A]) -> [B] {
    var result = Array<B>()
    for var i = 0, len = list.count; i < len; i++ {
      result.append(fn(list[i]))
    }
    return result
  }


  static func pluck<A, B>(property: A, _ list: [[A: B]]) -> [B?] {
    return self.map(self.get(property), list)
  }

}

func double(x: Int) -> Int {
  return x * 2
}

var list = [1, 2, 8]

var objs = [
  ["id": 1],
  ["id": 2],
  ["id": 3]
]

// non curried map
fn.map(double, list)

// curried map
var doubleList = fn.map(double)
doubleList(list)


// non curried get
fn.get("id", objs[0])

// curried get
fn.map(fn.get("id"), objs)


// non curried pluck
fn.pluck("id", objs)

swift swift3d.swift

swift3d.swift
import SceneKit
import XCPlayground

let width:CGFloat = 400
let height:CGFloat = 400

var view = SCNView(frame: CGRect(
    x: 0,
    y: 0,
    width: width,
    height: height))
var scene = SCNScene()
view.scene = scene
view.backgroundColor = NSColor.blackColor()
view.autoenablesDefaultLighting = true

var camera = SCNCamera()
var cameraNode = SCNNode()
cameraNode.camera = camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 3)
scene.rootNode.addChildNode(cameraNode)

for var i = 0; i < 50; i++ {
    var torus = SCNTorus(
        ringRadius: CGFloat(arc4random_uniform(150)) / 100.0,
        pipeRadius: 0.02)
    var torusNode = SCNNode(geometry: torus)
    scene.rootNode.addChildNode(torusNode)
    
    torus.firstMaterial.diffuse.contents = NSColor(
        calibratedHue: CGFloat(arc4random_uniform(100)) / 300.0 + 0.3,
        saturation: 0.5,
        brightness: 1.0,
        alpha: 0.95)
    torus.firstMaterial.specular.contents = NSColor.redColor()
    
    var spin = CABasicAnimation(keyPath: "rotation")
    spin.toValue = NSValue(SCNVector4:SCNVector4(
        x: CGFloat(random()),
        y: CGFloat(random()),
        z: CGFloat(random()),
        w: CGFloat(M_PI) * 2.0))
    spin.duration = NSTimeInterval(arc4random_uniform(20) + 5)
    spin.repeatCount = HUGE
    torusNode.addAnimation(spin, forKey: "spin")
}

XCPShowView("View", view)

swift UILabel子类使得设置填充非常容易。

UILabel子类使得设置填充非常容易。

UIBorderedLabel.swift
//
//  UIBorderedLabel.swift
//  standToMake
//
//  Created by Karl Oscar Weber on 9/13/14.
//  Copyright (c) 2014 Karl Oscar Weber. All rights reserved.
//
//  Thanks to: http://userflex.wordpress.com/2012/04/05/uilabel-custom-insets/

import UIKit

class UIBorderedLabel: UILabel {

    var topInset:       CGFloat = 0
    var rightInset:     CGFloat = 0
    var bottomInset:    CGFloat = 0
    var leftInset:      CGFloat = 0
    
    override func drawTextInRect(rect: CGRect) {
        var insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
        self.setNeedsLayout()
        return super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
    }

}