swift

Segue Lines

voor naar vc met storyboardId
let vc = storyboard?.instantiateViewControllerWithIdentifier("Second") as SecondViewController    presentViewController(vc, animated: true, completion: nil)

Tags: 

callback

class CallbackTest {
    var i = 5
    var callback: (Int -> ())? // NOTE: The optional callback takes an Int
    deinit { // NOTE: This is like -dealloc in Objective-C
        println("Deinit")
    }
}

var obj = CallbackTest()
obj.callback = {
    [unowned obj] // NOTE: Without this, deinit() would never be invoked!
    a in
    obj.i = a
}

Tags: 

enum

enum Shape {
    case Dot
    case Circle(radius: Double) // Require argument name!
    case Square(Double)
    case Rectangle(width: Double, height: Double) // Require argument names!
    func area() -> Double {
        switch self {
        case Dot:
            return 0
        case Circle(let r): // Assign the associated value to the constant 'r'
            return 3.14*r*r
        case Square(let l):
            return l*l
        case Rectangle(let w, let h):
            return w*h
        }
    }
}
var shape = Shape.Circle(radius: 3.0)
shape.area()//28.26
shape = Shape.Dot
shape.area()//0.0
shape = .Square(2)
shape.area()//4.0
shape = .Rectangle(width: 3, height: 4) // Argument names required
shape.area()//12.0

Tags: 

Hide status bar

add no to "View controller-based status bar appearance" in info.plist

add following to VC

override func prefersStatusBarHidden() -> Bool {
        return true
    }

Tags: 

uiswitch

mainSwitch = UISwitch(frame: CGRect(x: 100, y: 100, width: 0, height: 0))
   
    /* Adjust the off-mode tint color */
    mainSwitch.tintColor = UIColor.redColor()
    /* Adjust the on-mode tint color */
    mainSwitch.onTintColor = UIColor.brownColor()
    /* Also change the knob's tint color */
    mainSwitch.thumbTintColor = UIColor.greenColor()
   
    view.addSubview(mainSwitch)

@IBAction func soundEffectsSwitchChanged(sender: UISwitch) {
   
    if sender.on {
     
      Settings().setSoundFx(true)
   
    } else {
     
      Settings().setSoundFx(false)
    }
  }

Tags: 

uialert

var alert = UIAlertController(title: "No Internetconnection", message: "U heeft een internet connctie nodig om aankopen te kunnen doen", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Opnieuw", style: UIAlertActionStyle.Default, handler: { (paramAction:UIAlertAction!) in
     
      self.fetchCreditStoreItems()
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (paramAction:UIAlertAction!) in
     
      self.performSegueWithIdentifier("buyCreditsToHomeVC", sender: self)
    }))
    self.presentViewController(alert, animated: true, completion: nil)

met invullen
var controller:UIAlertController?
 
  override func viewDidLoad() {
    super.viewDidLoad()
   
    controller = UIAlertController(title: "Please enter your username",
      message: "This is usually 10 characters long",
      preferredStyle: .Alert)
   
    let action = UIAlertAction(title: "Next",
      style: UIAlertActionStyle.Default,
      handler: {[weak self] (paramAction:UIAlertAction!) in
       
        if let textFields = self!.controller?.textFields{
          let theTextFields = textFields as [UITextField]
          let userName = theTextFields[0].text
          println("Your username is \(userName)")
        }
       
      })
   
    controller!.addAction(action)
   
    controller!.addTextFieldWithConfigurationHandler(
      {(textField: UITextField!) in
        textField.placeholder = "XXXXXXXXXX"
      })
   
  }
 
  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.presentViewController(controller!, animated: true, completion: nil)
  }
 

simpel

  var controller:UIAlertController?
 
  override func viewDidLoad() {
    super.viewDidLoad()
   
    controller = UIAlertController(title: "Title",
      message: "Message",
      preferredStyle: .Alert)
   
    let action = UIAlertAction(title: "Done",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
      println("The Done button was tapped")
      })
   
    controller!.addAction(action)
   
  }
 
  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.presentViewController(controller!, animated: true, completion: nil)
  }

met action

controller = UIAlertController(
      title: "Choose how you would like to share this photo",
      message: "You cannot bring back a deleted photo",
      preferredStyle: .ActionSheet)
   
    let actionEmail = UIAlertAction(title: "Via email",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
        /* Send the photo via email */
      })
   
    let actionImessage = UIAlertAction(title: "Via iMessage",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
        /* Send the photo via iMessage */
      })
   
    let actionDelete = UIAlertAction(title: "Delete photo",
      style: UIAlertActionStyle.Destructive,
      handler: {(paramAction:UIAlertAction!) in
        /* Delete the photo here */
      })
   
    controller!.addAction(actionEmail)
    controller!.addAction(actionImessage)
    controller!.addAction(actionDelete)

of...

var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

handle actions
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    switch action.style{
    case .Default:
        println("default")

    case .Cancel:
        println("cancel")

    case .Destructive:
        println("destructive")
    }
}))

Tags: 

attributes text with smart range

    let string = "iOS SDK" as NSString
   
    let result = NSMutableAttributedString(string: string)
   
    let attributesForFirstWord = [
      NSFontAttributeName : UIFont.boldSystemFontOfSize(60),
      NSForegroundColorAttributeName : UIColor.redColor(),
      NSBackgroundColorAttributeName : UIColor.blackColor()
    ]
   
    let shadow = NSShadow()
    shadow.shadowColor = UIColor.darkGrayColor()
    shadow.shadowOffset = CGSize(width: 4, height: 4)
   
    let attributesForSecondWord = [
      NSFontAttributeName : UIFont.boldSystemFontOfSize(60),
      NSForegroundColorAttributeName : UIColor.whiteColor(),
      NSBackgroundColorAttributeName : UIColor.redColor(),
      NSShadowAttributeName : shadow,
    ]
   
    /* Find the string "iOS" in the whole string and sets its attribute */
    result.setAttributes(attributesForFirstWord,
      range: string.rangeOfString("iOS"))
   
   
    /* Do the same thing for the string "SDK" */
    result.setAttributes(attributesForSecondWord,
      range: string.rangeOfString("SDK"))

Tags: 

Loop through subviews

for view in self.view.subviews as [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // show error
            return
        }
    }
}

Tags: 

Remove Keyboard from view after typing txtField

// MARK: delegtes
   
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
   
   
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
       
        self.view.endEditing(true)
    }
   

Tags: 

uimaps location and annotation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!
   
    var manager:CLLocationManager
   
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
       
        //core location
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
       
       
        var lat:CLLocationDegrees = 40.748473
        var long:CLLocationDegrees = -73.985417
       
        var latDelta:CLLocationDegrees = 0.01
        var longDelta:CLLocationDegrees = 0.01
       
        var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
        var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, long)
       
        var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
        mapView.setRegion(region, animated: true)
       
        var annotation:MKPointAnnotation = MKPointAnnotation()
        annotation.coordinate = location
        annotation.title = "Statue of Liberty"
        annotation.subtitle = "One day I will come by"
       
        mapView.addAnnotation(annotation)
       
       
    }

Tags: 

Gesture

var uilongPRec = UILongPressGestureRecognizer(target: self, action: "lpAction:")//funcName: : for adding var to fund!
        uilongPRec.minimumPressDuration = 1.5 //time for long press
        mapView.addGestureRecognizer(uilongPRec) // add long press to mapview

func lpAction(gestureRecognizer: UIGestureRecognizer){
       
        var touchPoint = gestureRecognizer.locationInView(self.mapView)

        var newCoord:CLLocationCoordinate2D = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
       
        var annotation:MKPointAnnotation = MKPointAnnotation()
        annotation.coordinate = newCoord
        annotation.title = "New Ann"
        annotation.subtitle = "One day I will come by"
       
        mapView.addAnnotation(annotation)
       
       
       
    }

Tags: 

Timer

timer = NSTimer.scheduledTimerWithTimeInterval(
            0.1,
            target: self,
            selector: "updateTime",
            userInfo: nil,
            repeats: true
        )

Tags: 

Animation

override func viewDidAppear(animated: Bool) {
       
        UIView.animateWithDuration(1.0, animations: { () -> Void in
           
            self.image.center = CGPointMake(self.image.center.x + 400, self.image.center.y)
            self.image.alpha = 1.0
            self.image.frame = CGRectMake(0 , 0, 320, 320)
        })
    }

Tags: 

Extensions Convenience init!

extension UIColor{
   
    convenience init(red: Int, green: Int, blue: Int)
    {
        let newRed   = CGFloat(Double(red) / 255.0)
        let newGreen = CGFloat(Double(green) / 255.0)
        let newBlue  = CGFloat(Double(blue) / 255.0)
       
        self.init(red: newRed, green: newGreen, blue: newBlue, alpha: CGFloat(1.0))
    }
}

let swiftOrange = UIColor(red: 255, green: 149, blue: 0)
let swColor = UIColor(red:34, green:223, blue:123)

Tags: 

Abstract Factory

protocol Decimal {
    func stringValue() -> String
}

protocol NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal
}

// Number implementations.

struct NextStepNumber : Decimal {
    private var nextStepNumber : NSNumber

    func stringValue() -> String { return nextStepNumber.stringValue }
}

struct SwiftNumber : Decimal {
    private var swiftInt : Int

    func stringValue() -> String { return "\(swiftInt)" }
}

// Factories.

class NextStepNumberFactory : NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal {
        return NextStepNumber(nextStepNumber:NSNumber(longLong:(string as NSString).longLongValue))
    }
}

class SwiftNumberFactory : NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal {
        return SwiftNumber(swiftInt:(string as NSString).integerValue)
    }
}

// Abstract factory.

enum NumberType {
    case NextStep, Swift
}

class NumberAbstractFactory {
    class func numberFactoryType(type : NumberType) -> NumberFactoryProtocol {

        switch type {
            case .NextStep:
                    return NextStepNumberFactory()
            case .Swift:
                    return SwiftNumberFactory()
        }
    }
}

let factoryOne = NumberAbstractFactory.numberFactoryType(.NextStep)
let numberOne = factoryOne.numberFromString("1")
numberOne.stringValue()

let factoryTwo = NumberAbstractFactory.numberFactoryType(.Swift)
let numberTwo = factoryTwo.numberFromString("2")
numberTwo.stringValue()

Tags: 

Builder

protocol ThreeDimensions {
    var x: Double? {get}
    var y: Double? {get}
    var z: Double? {get}
}

class Point : ThreeDimensions {
    var x: Double?
    var y: Double?
    var z: Double?

    typealias PointBuilderClosure = (Point) -> ()

    init(buildClosure: PointBuilderClosure) {
        buildClosure(self)
    }
}

let fancyPoint = Point { point in
point.x = 0.1
point.y = 0.2
point.z = 0.3
}

fancyPoint.x
fancyPoint.y
fancyPoint.z
Shorter but oh-so-ugly alternative:

let uglierPoint = Point {
$0.x = 0.1
$0.y = 0.2
$0.z = 0.3
}

Tags: 

SingletonClass

class SingletonClass {
    class var shared : SingletonClass {

        struct Static {
            static let instance : SingletonClass = SingletonClass()
        }

        return Static.instance
    }
}

use:
let instance = SingletonClass.shared

Tags: 

uitextfield

var txtField: UITextField = UITextField()
    txtField.frame = CGRectMake(50, 70, 200, 30)
    txtField.backgroundColor = UIColor.grayColor()
    self.view.addSubview(txtField)

Tags: 

uilabel

   
var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label..numberOfLines = 0
label.text = "test label"
self.view.addSubview(label)

Multiline

label.lineBreakMode = .ByWordWrapping
label.numberOfLines = 0

Tags: 

uibutton

let button = UIButton(type: .Custom)
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)

button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)

Tags: 

strings

for character in "mouse"{
println(character)
}
m
o
u
s
e

let a 3 , b= 5
// "3 times 5 is 15"
let math result = "\(a) times \(b) is \(a*b)"

Tags: 

declaring variables

var mutableDouble = 1.0
mutableDouble = 2.0

let constantDouble = 1.0
// errror constantDouble = 2.0

var optionalDouble:Double ?= nil
optionalDouble = 1.0

if let definiteDouble = optionalDouble {
definiteDouble
}

variable types

Int 1,2,500
Float 0.5
Double
Bool true, false
String "string"
Classname UIView, UIImage

Tags: 

Pages

Subscribe to RSS - swift