swift

Text Spacing

extension UILabel{
    func addTextSpacing(spacing: CGFloat){
        let attributedString = NSMutableAttributedString(string: self.text!)
        attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.text!.characters.count))
        self.attributedText = attributedString
    }
}

cell.titleLabel.addTextSpacing(1.4)

Tags: 

moving/renaming xcode

from:
/Applications/Xcode.app
=>
/Applications/xcode/Xcode73.app

sudo xcode-select -switch /Applications/xcode/Xcode73.app/Contents/Developer

remove xcode plugins:
rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/*

Tags: 

nd char in String

extension String {

    func index(at offset: Int, from start: Index? = nil) -> Index?
    {
        return index(start ?? startIndex, offsetBy: offset, limitedBy: endIndex)
    }

    func character(at offset: Int) -> Character?
    {
        precondition(offset >= 0, "offset can't be negative")
        guard let index = index(at: offset) else { return nil }
        return self[index]
    }

    subscript(_ range: CountableRange<Int>) -> Substring
    {
        precondition(range.lowerBound >= 0, "lowerBound can't be negative")
        let start = index(at: range.lowerBound) ?? endIndex
        return self[start..<(index(at: range.count, from: start) ?? endIndex)]
    }

    subscript(_ range: CountableClosedRange<Int>) -> Substring
    {
        precondition(range.lowerBound >= 0, "lowerBound can't be negative")
        let start = index(at: range.lowerBound) ?? endIndex
        return self[start..<(index(at: range.count, from: start) ?? endIndex)]
    }

    subscript(_ range: PartialRangeUpTo<Int>) -> Substring
    {
        return prefix(range.upperBound)
    }

    subscript(_ range: PartialRangeThrough<Int>) -> Substring
    {
        return prefix(range.upperBound+1)
    }

    subscript(_ range: PartialRangeFrom<Int>) -> Substring
    {
        return suffix(max(0, count-range.lowerBound))
    }

}

extension Substring {
    var string: String { return String(self) }
}

var abc = "abcdefg"
//2nd char
String(abc[abc.characters.startIndex.advancedBy(1)]) //"b"

get range with
extension String {
   
    subscript (i: Int) -> Character
    {
        return self[self.startIndex.advancedBy(i)]
    }
   
    subscript (r: Range<Int>) -> String
    {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        return self[Range(start ..< end)]
    }
}

results: abc[0...1] // "ab"
abc[1] = "a"
Or
Array(abc.characters)[1] //"b"

Tags: 

Same Random Seed

var r = srand48(1)  //()
var r1 = drand48()  //0.04163034477187821
var r2 = drand48()  //0.4544924447286292
var r3 = drand48()  //0.8348172181669149


var s = srand48(1)
var s1 = drand48()  //0.04163034477187821
var s2 = drand48()  //0.4544924447286292
var s3 = drand48()  //0.8348172181669149

Tags: 

Shuffle

Fisher–Yates shuffle

func shuffle<T>(arr:[T]) ->[T]
{
    var array:[T] = arr
    var m = array.count
    var t :T
    var i = 0
   
    while (m > 0) {
       
        m -= 1
        i = Int(arc4random_uniform(UInt32(m)))
       
        t = array[m]
        array[m] = array[i]
        array[i] = t
    }
   
    return array
}

with gameplaykit
then NSArray has extended func .shuffled()

import GameplaKit
(array as NSArray).shuffled()

or with GKRandomSource
import GameplayKit

var arr = [1,2,3,4,5,6,7]

let source = GKRandomSource.sharedRandom()
source.arrayByShufflingObjects(in: arr) // [3, 7, 5, 1, 4, 2, 6]

with seed

import GameplayKit

var arr = [1,2,3,4,5,6,7]

let source = GKLinearCongruentialRandomSource()
source.seed = 12345
source.arrayByShufflingObjects(in: resultsArray)

Tags: 

Icon create

after: brew install imagemagick
create iconcreate.sh

#!/bin/bash
for size in {76,40,29,60,57,50,72,167}; do for scale in {1,2,3}; do
    if [[ $scale == 1 ]]; then
        filename="icon_${size}.png"
    else
        filename="icon_${size}@${scale}x.png"
    fi
    gm convert "icon.png" -resize "$(( $scale * $size ))x$(( $scale * $size ))" $
done; done

or
sh iconcreate.sh icon.png

convert $1 -resize 16x16      Icon-16.png
convert $1 -resize 32x32      Icon-16@2x.png
convert $1 -resize 29x29      Icon-Small-29.png          # Settings on iPad and iPhone, and Spotlight on iPhone
convert $1 -resize 58x58      Icon-Small-29@2x.png
convert $1 -resize 87x87      Icon-Small-29@3x.png
convert $1 -resize 32x32      Icon-32.png
convert $1 -resize 64x64      Icon-32@2x.png
convert $1 -resize 40x40      Icon-Small-40.png       # Spotlight
convert $1 -resize 80x80      Icon-Small-40@2x.png       # Spotlight
convert $1 -resize 120x120    Icon-Small-40@3x.png       # Spotlight
convert $1 -resize 50x50      Icon-Small-50.png       # Spotlight on iPad 1/2
convert $1 -resize 57x57      Icon-57.png                # Home screen on non-Retina iPhone/iPod
convert $1 -resize 114x114    Icon-57@2x.png             # Home screen for Retina display iPhone/iPod
convert $1 -resize 120x120    Icon-60@2x.png          # Home screen on iPhone/iPod Touch with retina display
convert $1 -resize 180x180    Icon-60@3x.png          # Home screen on iPhone 6 Plus
convert $1 -resize 72x72      Icon-72.png             # App Store and Home screen on iPad
convert $1 -resize 144x144    Icon-72@2x.png          # Home screen for "The New iPad"
convert $1 -resize 76x76      Icon-76.png             # Home screen on iPad
convert $1 -resize 152x152    Icon-76@2x.png          # Home screen on iPad with retina display
convert $1 -resize 228x228    Icon-76@3x.png
convert $1 -resize 83.5x83.5  Icon-83,5.png
convert $1 -resize 167x167    Icon-83,5@2x.png
convert $1 -resize 128x128    Icon-128.png
convert $1 -resize 256x256    Icon-128@2x.png
convert $1 -resize 256x256    Icon-256.png
convert $1 -resize 512x512    Icon-256@2x.png
convert $1 -resize 512x512    Icon-512.png
convert $1 -resize 1024x1024  iTunesArtwork@2x.png   # App list in iTunes for devices with retina display
convert $1 -resize 1024x1024  Icon-512@2x.png
convert $1 -resize 512x512    iTunesArtwork.png       # Ad Hoc iTunes

NSUserDefaults [Int:Int]

load

if let data = NSUserDefaults.standardUserDefaults().objectForKey( "averagesPerLevel") as? NSData
{
    let object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [Int: Int]
    print("average cached : \(object))")
}

save

NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(self.globalAverages!.averagesPerLevel), forKey:"averagesPerLevel")

Tags: 

Xcode snippet

Code Snippet Library within Xcode

variable to edit is within <# var #>

// FIXME: <# Subject #>

to make todo / fix into warning

add run script in Build Phases
shell: /bin/sh
(tick 'Show environment variables in build log')

TAGS="TODO:|FIXME:"
find "${SRCROOT}" \( -name "*.h" -or -name "*.m" -or -name "*.swift" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($TAGS).*\$" | perl -p -e "s/($TAGS)/ warning: \$1/"

Tags: 

nscodernight

let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
XCPlaygroundPage.currentPage.liveView = containerView
containerView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

var view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 300, height: 200)
view.backgroundColor = #colorLiteral(red: 0.9346159697, green: 0.6284804344, blue: 0.1077284366, alpha: 1)
containerView.addSubview(view)

let timing = UICubicTimingParameters(animationCurve: .easeIn)

let animator = UIViewPropertyAnimator(duration: 5.0, timingParameters: timing)
animator.addAnimations
  {
    view.center = containerView.center
}



let scene = UIViewPropertyAnimator(duration: 2.0, timingParameters: timing)
scene.addAnimations {
  containerView.backgroundColor = #colorLiteral(red: 0.2818343937, green: 0.5693024397, blue: 0.1281824261, alpha: 1)
}
scene.addCompletion { (_) in
  view.backgroundColor = #colorLiteral(red: 0.1991284192, green: 0.6028449535, blue: 0.9592232704, alpha: 1)
}
animator.addCompletion
  { _ in
      scene.startAnimation()
   
}
animator.startAnimation()

Tags: 

TVOS light dark

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
// Is userInterfaceStyle available?
guard(traitCollection.response(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
  else{ return}
guard(traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle)
  else{ return}
}

class AppearanceViewController: UIViewController
{
var style: UIUserInterfaceStyle = /light
override init(nibName nibNameOrNil: String?, bundle nibNameOrNil: Bundle?){...}

required init?(coder aDecoder: NSCoder) {...}

var viewController: UIViewController
{
  get {return self}
  set {
  //override trait collection
let traitCollection = UITraitCollection(userInterfaceStyle: style)
self.setOverrideTraitCollection(traitCollection, forChildViewController: newValue)

//add child view controller
self.addChildViewController(newValue)
newValue.view.frame = view.bounds
self.view.addSubview(newValue.view)
newValue.didMove(toParentViewController: self)

  }
}
}

to tvos10

info.plist
user Interface style => automatic

storyboard

Interface Builder Document
v use Trait Variations

App delegate

.. didFinishLaunchingWithOptions ..
let light = UITraitCollection(userInterfaceStyle:.light)
let backgroundColor = UIColor(white:1 alpha:  0.5)
UICOllectionViewCell.forTraitCollection(light).backgroundColor = backgroundColor

let dark = UITraitCollection(userInterfaceStyle:.dark)
let darkbackgroundColor = UIColor(white:0.2 alpha:  0.8)
UICOllectionViewCell.forTraitCollection(dark).backgroundColor = darkbackgroundColor

in VC

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
// Is userInterfaceStyle available?
guard( traitCollection.responds(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
  else{ return}
guard(traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle)
  else{ return}
}

if traitCollection.userInterfaceStyle == .dark
{
..do this
}
else
{
..do that
}

Tags: 

Random In

func randomNumberIn(range:Range<Int>)->Int
{
    let result = 0
    let random = range.minElement()!  + Int(arc4random_uniform(UInt32((range.maxElement()!+1) - range.minElement()!)))
    if random != 0
    {
        return random
    }
    return result
}

bv:
let r = randomNumberIn(0...255)
let g = randomNumberIn(0...255)
let b = randomNumberIn(0...255)
backgroundColor = UIColor(red: r, green: g, blue: b)

gameplaykit

let source = GKPerlinNoiseSource(
frequency:2,
octave:3,
persistance: 0.5,
lacunarity: 2
)
let noise = GKNoise(source)

Tags: 

Looping

Looping n times

for var i = 0; i < 10; i++ {
    print(i)
}

// use this:
for i in 0..<10 {
    print(i)
}

Looping n times in reverse

for var i = 10; i > 0; i-- {
    print(i)
}

// use this
for i in (1...10).reverse() {
    print(i)
}

Looping with Stride

for var i = 0; i < 10; i += 2 {
    print(i)
}

// use this
for i in 0.stride(to: 10, by: 2) {
    print(i)
}

Looping through Array Values

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print(someNumbers[i])
}

// use this
for number in someNumbers {
    print(number)
}

// or this
someNumbers.forEach { number in
    print(number)
}

Reverse Looping through Array Values

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/* 100, 83, 8, 6, 45, 3, 2 */

// instead of this
for var i = someNumbers.count - 1; i >= 0; i-- {
    print(someNumbers[i])
}

// use this
for number in someNumbers.reverse() {
    print(number)
}

Looping Through an Array with Index

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/*
1: 2
2: 3
3: 45
4: 6
5: 8
6: 83
7: 100
*/

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print("\(i + 1): \(someNumbers[i])")
}

// use this
for (index, number) in someNumbers.enumerate() {
    print("\(index + 1): \(number)")
}

// or this
someNumbers.enumerate().forEach { (index, number) in
    print("\(index + 1): \(number)")
}

Looping Through Array Indices

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/* 0, 1, 2, 3, 4, 5, 6 */

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print(i)
}

// use this
for index in someNumbers.indices {
    print(index)
}

from: Natasha the Robot

Tags: 

3d touch

Voor icon on 'desktop'

In info.plist
add:

<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconFile</key>
<string>button_continue</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Continue last puzzle</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Continue</string>
<key>UIApplicationShortcutItemType</key>
<string>com.company.bla.bla</string>
</dict>
<dict>
<key>UIApplicationShortcutItemIconFile</key>
<string>button_puzzles</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Choose new puzzle</string>
<key>UIApplicationShortcutItemTitle</key>
<string>New puzzle</string>
<key>UIApplicationShortcutItemType</key>
<string>com.company.bla.bla</string>
</dict>
</array>

in UIView

import UIKit
import AudioToolbox

protocol SelectLetterViewDelegate: class
{
    func foundChar(foundChar:String)
    func addChar(foundChar:String)
}

class SelectLetterView:UIView
{
   
    weak var delegate: SelectLetterViewDelegate?
   
    var charsToChoose =
        [">","A","B","C","D","E","F",
         "G","H","I","J","K","L",
         "M","N","O","P","Q","R",
         "S","T","U","V","W","X",
         "Y","Z","*"
    ]
    var lastChosenString = ""
    var charCollection: [UILabel] = []

    var clickon = false
    var useForceTouch = false
   
    //Mark: - Init / setup
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        self.initialize()
    }
   
    convenience init() {
        self.init(frame: CGRectZero)
       
        self.initialize()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func initialize() {
        addCharsToView()
        print("traitCollection.forceTouchCapability \(traitCollection.forceTouchCapability)")
        if traitCollection.forceTouchCapability == UIForceTouchCapability.Available
        {
            print("we have forceTouchCapability")
            useForceTouch = true
        }
        else
        {
            print("we dont have forceTouchCapability...")
        }
    }
   
    //Mark: - Layout
    func addCharsToView()
    {
        if charsToChoose.count > 0
        {
            let dimensionHeight:CGFloat = self.frame.height / CGFloat(charsToChoose.count)
            for i in 0 ..< charsToChoose.count
            {
                let view = UILabel(frame: CGRectMake(0,CGFloat(i) * dimensionHeight,self.frame.width,dimensionHeight))
                if i%2==0
                {
                    view.backgroundColor = .darkGrayColor()
                }
                else
                {
                    view.backgroundColor = .clearColor()
                }
                view.text = "\(charsToChoose[i])"
                view.textColor = .whiteColor()
                view.textAlignment = .Center
                charCollection.append(view)
                self.addSubview(view)
            }
        }
    }
   
   
    //Mark: - Touches
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
    var canAddChar                      = false
    var lastFractionPressure:CGFloat    = 0
   
    func reactToTouch(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
       
        if let touch = touches.first
        {
            let fractionTouchPressure = touch.force/touch.maximumPossibleForce
            if fractionTouchPressure >= 1.0 && touch.force > 0 && touch.maximumPossibleForce > 0 && clickon == false && lastFractionPressure == 0
            {
                lastFractionPressure = fractionTouchPressure
                clickon = true
                canAddChar = true
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
                dispatch_after(200, dispatch_get_main_queue())
                {
                    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate)
                }
                print("click On \(touch.force/touch.maximumPossibleForce)")
               
            }
            if clickon == true && fractionTouchPressure <= 0.2
            {
                print("click off")
                clickon = false
                lastFractionPressure = 0
            }
            let position :CGPoint = touch.locationInView(self)
            if event != nil
            {
                foundCharOnTouch(position,event: event!, clickon: clickon)
            }
        }
    }
   
    func foundCharOnTouch(point:CGPoint,event:UIEvent,clickon:Bool)
    {
        for l in self.subviews
        {
            if l is UILabel
            {
                if let label = l as? UILabel
                {
                   
                    if label.pointInside(convertPoint(point, toView: label), withEvent: event)
                    {
                        lastChosenString = label.text!
                        if clickon == false
                        {
                            delegate?.foundChar(label.text!)
                        }
                        else
                        {
                            if lastFractionPressure != 0 && canAddChar
                            {
                                canAddChar = false
                                delegate?.addChar(label.text!)
                               
                            }
                        }
                    }
                }
            }
          
        }
    }
}

AppDelegate

import UIKit


enum DGShortcutItemType: String {
    case Continue
    case NewPuzzle
   
    init?(shortcutItem: UIApplicationShortcutItem) {
        guard let last = shortcutItem.type.componentsSeparatedByString(".").last else { return nil }
        self.init(rawValue: last)
    }
   
    var type: String {
        return NSBundle.mainBundle().bundleIdentifier! + ".\(self.rawValue)"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
            handleShortcutItem(shortcutItem)
        }
        return true
    }


    func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
        handleShortcutItem(shortcutItem)
    }

    private func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) {
        if let rootViewController = window?.rootViewController, let shortcutItemType = DGShortcutItemType(shortcutItem: shortcutItem) {
            rootViewController.dismissViewControllerAnimated(false, completion: nil)
            let alertController = UIAlertController(title: "", message: "", preferredStyle: .Alert)
           
            switch shortcutItemType {
            case .Continue:
                alertController.message = "Continue"
                break
            case .NewPuzzle:
                alertController.message = "New Puzzle"
                break
            }
           
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            rootViewController.presentViewController(alertController, animated: true, completion: nil)
        }
    }
}

Tags: 

UIView init

class AView:UIView
{
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        self.initialize()
    }
   
    convenience init() {
        self.init(frame: CGRectZero)
       
        self.initialize()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func initialize() {
        doAFunc()
    }
}

Tags: 

Enum with var and func

public enum LanguageForGame:Int
{
   
    case All    = 1,
    Dutch       = 2,
    French      = 3,
    English     = 4,
    Spanish     = 5,
    German      = 6,
    Italian     = 7,
    Swedish     = 8,
    Danish      = 9
   
    public var createLanguageCode:String
    {
        switch self {
        case .English:
            return "en"
        case .German:
            return "de"
        case .Danish:
            return "da"
        case .Swedish:
            return "sv"
        case .Dutch:
            return "nl"
        case .Spanish:
            return "es"
        case .French:
            return "fr"
        case .Italian:
            return "it"
        case .All:
            return "*"
        }
    }
   
    public var createCultureCodeWithMinus:String
    {
        switch self {
        case .English:
            return "en-GB"
        case .German:
            return "de-DE"
        case .Danish:
            return "da-DK"
        case .Swedish:
            return "sv-SE"
        case .Dutch:
            return "nl-NL"
        case .Spanish:
            return "es-ES"
        case .French:
            return "fr-FR"
        case .Italian:
            return "it-IT"
        case .All:
            return "*"
           
        }
    }
    public var createCultureCodeWithUnderScore:String
    {
        switch self {
        case .English:
            return "en_GB"
        case .German:
            return "de_DE"
        case .Danish:
            return "da_DK"
        case .Swedish:
            return "sv_SE"
        case .Dutch:
            return "nl_NL"
        case .Spanish:
            return "es_ES"
        case .French:
            return "fr_FR"
        case .Italian:
            return "it_IT"
        case .All:
            return "*"
           
        }
    }
   
    public static func getLanguageNumberFromLanguagesForGame(langString:String)->Int
    {
       
        switch langString
        {
        case "en":
            return LanguageForGame.English.rawValue
        case "de":
            return LanguageForGame.German.rawValue
        case "da":
            return LanguageForGame.Danish.rawValue
        case "se":
            return LanguageForGame.Swedish.rawValue
        case "nl":
            return LanguageForGame.Dutch.rawValue
        case "es":
            return LanguageForGame.Spanish.rawValue
        case "fr":
            return LanguageForGame.French.rawValue
        case "it":
            return LanguageForGame.Italian.rawValue
        default:
            return LanguageForGame.All.rawValue
        }
       
    }
   
}

struct HashableSequence<T: Hashable>: SequenceType {
    func generate() -> AnyGenerator<T> {
        var i = 0
        return AnyGenerator {
            guard sizeof(T) == 1 else {
                return nil
            }
            let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
            if next.hashValue == i {
                i += 1
                return next
            }
           
            return nil
        }
    }
}
extension Hashable {
    static func enumCases() -> Array<Self> {
        return Array(HashableSequence())
    }
   
    static var enumCount: Int {
        return enumCases().count
    }
}

let numberOfLanguages = LanguageForGame.enumCount // 9

Tags: 

Switch Button

class SwitchButton: UIButton
{
   
    var imageOn:UIImage?
    var imageOff:UIImage?
    var stateOn = true
        {
        didSet
        {
            setImageToState(stateOn)
        }
    }
   
   
   
    //MARK: - VC
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
   
    convenience init(frame: CGRect, imgOn:UIImage, imgOff:UIImage)
    {
       
        self.init(frame: frame)
       
        self.imageOn = imgOn
        self.imageOff = imgOff
        if let img = imageOn as UIImage?
        {
            setImage(img, forState: .Normal)
        }
        self.addTarget(self, action: #selector(SwitchButton.changeState), forControlEvents: UIControlEvents.TouchUpInside)
       
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func changeState()
    {
        self.stateOn = !self.stateOn
    }
   
    func setImageToState(On:Bool)
    {
        switch On {
        case false:
            setImage(imageOff, forState: .Normal)
        default:
            setImage(imageOn, forState: .Normal)
        }
    }
   
}

Tags: 

Installing CocoaPods on OS X 10.11

Installing CocoaPods on OS X 10.11

$ sudo chmod -R 755 /usr/local/bin
$ sudo gem uninstall cocoapods
Remove executables:
pod, sandbox-pod

in addition to the gem? [Yn] Y

$ gem install cocoa pods

$ pod install

==
OR
==

These instructions were tested on all betas and the final release of El Capitan.

Custom GEM_HOME

This is the solution when you are receiving Above Error

$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version

Tags: 

Cocoapods in Playgrounds

Install:

$ gem install cocoapods-playgrounds
Create a Playground with Alamofire:

$ pod playgrounds Alamofire
Create a Playground with multiple pods:

$ pod playgrounds RxSwift,RxCocoa
The new Playground will automatically open.

You will have to first build the project, to enable the pods, then the Playground will be available.

===
Or:

During the app development, you may find a third-party libraries or frameworks may save you a lot of time and let you focus on your fancy features. However, you always want to verify whether the functions provided by the library are what you expect. To do so, playground is a prefect place to test them out.

Using CocoaPods
CocoaPods manages library dependencies for your Xcode projects.
You first need to install CocoaPods. Open Terminal and enter the following command:

sudo gem install cocoapods

Enter your password when requested. Then enter this command in Terminal to complete the setup:

pod setup --verbose

This process will likely take a few minutes, and the verbose option logs progress as the process runs, allowing you to watch the process instead of seeing a seemingly “frozen” screen.

Installing Your Dependency
Create a Xcode project if you don't have one, and then close Xcode.
Open Terminal and navigate to the directory that contains your project:

cd ~/Path/To/Folder/Containing/YourProject

Next, enter this command:

pod init

This creates a Podfile for your project.
Open the Podfile using Xcode for editing, and you can use this command:

open -a Xcode Podfile

The default Podfile looks like this:

# Uncomment this line to define a global platform for your project
# platform :ios, '8.0'

target 'YourProject' do

end

target 'YourProjectTests' do

end

Change it with following:

platform :ios, "8.0"
use_frameworks!

link_with 'YourProject', 'YourProjectTests'
pod 'Alamofire'
pod 'SwiftyJSON'

In my example, I am going to use Alamfire and SwiftyJSON libraries in my project. You can change it to whatever library you would like to play with.

Jump back the Terminal, and use this command to install pods:

pod install

And after the installation, the last line of the output should be like this:

[!] Please close any current Xcode sessions and use `YourProject.xcworkspace` for this project from now on.

The CocoaPads creates a workspace based on your project, as the command-line warning mentioned, you must always use the workspace and not the project, otherwise you’ll encounter build errors.

By using a workspace, all dependencies are available cross the workspace.
Create a playground in the workspace, and add it to the Podfile with following:

platform :ios, "8.0"
use_frameworks!

link_with 'YourProject', 'YourProjectTests', 'YourPlayground'
pod 'Alamofire'
pod 'SwiftyJSON'

You can import and use the pod your have installed in the playground:

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

import SwiftyJSON
import Alamofire

Congratulations, you can play with your third-party pods in Playground!

Tags: 

App without Storyboard

iOS 14

  • remove main story board from files
  • from => info remove 'main storyboard file base name'
  • then drill down in scene manifest to remove main item 0 main file name and remove

adjust code in sceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = ViewController()
        window.makeKeyAndVisible()
        self.window = window
    }
...

Project > Targets > Deployment Info

empty "Main Interface"

Remove Reference in Info.plist

Open your Info.plist

    • Click the arrow at the leftmost of Application Scene Manifest (UIApplicationSceneManifest) key to expand
      Click the arrow at the leftmost of Scene Configuration (UISceneConfigurations) key to expand
      Click the arrow at the leftmost of Application Session Role (UIWindowSceneSessionRoleApplication) key to expand
      Click the arrow at the leftmost of First Item (Item 0) key to expand
      Remove the key Storyboard Name (UISceneStoryboardFile)
  • From IOS 13

    Not in appDelegate anymore...
    in SceneDelegate:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
            guard let windowScene = (scene as? UIWindowScene) else { return }
            window = UIWindow(windowScene: windowScene)
            window?.rootViewController = MockupIntroVC()
            window?.backgroundColor = .systemBackground // optional
            window?.makeKeyAndVisible()
        }

    AppDelegate

    var window: UIWindow?

      func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        if let window = window {
          window.backgroundColor = UIColor.whiteColor()
          window.rootViewController = ViewController()
          window.makeKeyAndVisible()
        }
        return true
      }

    ViewController

    class ViewController: UIViewController {

      var button :UIButton!
     

      override func viewDidLoad() {
        super.viewDidLoad()
       
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = .redColor()
        setupLayout()
      }
     

      func setupLayout()
      {
        if button == nil
        {
          self.view.addSubview(createButton(self))
          }
      }

      func buttonPressed(sender:UIButton)
      {
        showNewViewController(SecondViewController())
      }
      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        print("\(__FUNCTION__)")
      }

      deinit
      {
        print("\(__FUNCTION__) v1")
      }

    }

    // General funcs for demo purposes
    func createButton(vc:UIViewController)->UIButton
    {
      let button:UIButton
      button = UIButton(frame: CGRectMake(0,0,123,123))
      button.backgroundColor = .yellowColor()
      button.addTarget(vc, action: "buttonPressed:", forControlEvents: .TouchUpInside)
      button.setTitle("Button", forState: .Normal)
      return button
    }

    func showNewViewController(vc:UIViewController)
    {
      UIApplication.sharedApplication().keyWindow!.rootViewController = vc.self

    }

    SecondViewController

    class SecondViewController: UIViewController {

      var button :UIButton!
      override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = .blueColor()
        setupLayout()
          }

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


      func setupLayout()
      {
        if button == nil
        {
          self.view.addSubview(createButton(self))
        }
      }
     
      func buttonPressed(sender:UIButton)
      {
        showNewViewController(ViewController())
      }
      deinit
      {
        print("\(__FUNCTION__) v2")
      }
    }

    Tags: 

    find top viewcontroller

    extension UIApplication {
      class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
          return topViewController(nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
          if let selected = tab.selectedViewController {
            return topViewController(selected)
          }
        }
        if let presented = base?.presentedViewController {
          return topViewController(presented)
        }
        return base
      }
    }

    and use like

    if let topvc = UIApplication.topViewController()
              {
                if topvc is HomeVC
                {
                  let vc = topvc as! HomeVC
                  vc.updateGcmMessageButton()
                }
              }

    Tags: 

    find in array times, Slow in build functionality...

    Consider this

    func getCell(x:Int, y:Int) -> GameBoardCell?{
        let start1 = NSDate()
        if let r = gameBoardCells.indexOf({$0.xPos == x && $0.yPos == y})
        {
          let end1 = NSDate()
          let timeInterval: Double = end1.timeIntervalSinceDate(start1)
          print("Time to evaluate problem1: \(timeInterval)")
          //return gameBoardCells[i]
        }
       
       
        let start2 = NSDate()
        let result = gameBoardCells.filter ({$0.xPos == x && $0.yPos == y})
        if result.count > 0
        {
          let end2 = NSDate()
          let timeInterval2: Double = end2.timeIntervalSinceDate(start2)
          print("Time to evaluate problem2: \(timeInterval2) count \(result.count)")
         
          //return result.first
        }
       
       
        let start3 = NSDate()
        for c in gameBoardCells
        {
          if(c.xPos == x && c.yPos == y)
          {
            let end3 = NSDate()
            let timeInterval3: Double = end3.timeIntervalSinceDate(start3)
            print("Time to evaluate problem3: \(timeInterval3)")
            return c
          }
        }
        return nil
      }

    in the beginning with small array
    Time to evaluate problem1: 0.000268995761871338
    Time to evaluate problem2: 0.000285029411315918 count 1
    Time to evaluate problem3: 0.000150978565216064

    results with large array
    Time to evaluate problem1: 3.80277633666992e-05
    Time to evaluate problem2: 0.000289022922515869 count 1
    Time to evaluate problem3: 2.3961067199707e-05

    So Old school looping is quicker than using the build in functionality

    Tags: 

    Elapsed Time

    let start1 = NSDate()
    //.. Do Something ..
    let end1 = NSDate()
    let timeInterval: Double = end1.timeIntervalSinceDate(start1)
    print("Elapsed Time: \(timeInterval)")

    Tags: 

    Sweet Loops

    for section in sections {
        var foundTheMagicalRow = false
        for row in rows {
            if row.isMagical {
                foundTheMagicalRow = true
                break
            }
        }
        if foundTheMagicalRow {
            //We found the magical row!
            //No need to continue looping through our sections now.
            break
        }
    }

    is the same as:
    sectionLoop: for section in sections {
        rowLoop: for row in rows {
            if row.isMagical {
                break sectionLoop
            }
        }
    }

    from:
    http://krakendev.io/

    Tags: 

    Record crashes

    General func

    func exceptionHandler(exception : NSException) {
      let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
     

        defaults.setObject(exception.debugDescription , forKey: "exception")
        defaults.synchronize()
      print("exc: \(exception)")
      print("exc call stack: \(exception.callStackSymbols)")
    }

    in didFinishLaunchingWithOptions

    NSSetUncaughtExceptionHandler(exceptionHandler)
        if NSUserDefaults.standardUserDefaults().objectForKey("exception") != nil
        { .. }

    create crash for example with

    let array = NSArray()
    let elem = array.objectAtIndex(99)

    Tags: 

    Inheritance with didSet

    class A:UIView
    {
      var b:Int
     
      override init(frame: CGRect) {
        b = 1
        super.init(frame: frame)
      }

      required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
      }
     
      func bla()
      {
       
      }

    }

    class B:A  {

      override var b:Int
      {
        didSet
        {
          print("b \(b)")
        }
      }

      func bcd()
      {
       
      }
     
      override func bla()
      {
       
      }

    }

    Tags: 

    Reachability

    swift 2.0

     
    public class ReachabilityToConnection {
        class func isConnectedToNetwork() -> Bool {
          var zeroAddress = sockaddr_in()
          zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
          zeroAddress.sin_family = sa_family_t(AF_INET)
          let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
          }
          var flags = SCNetworkReachabilityFlags()
          if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
          }
          let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
          let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
          return (isReachable && !needsConnection)
        }
    }

    Tags: 

    find in array and delte

      if let foundIndex = find(self.friends!, friend)
    {

             //remove the item at the found index
             self.friends!.removeAtIndex(foundIndex)

    }

    swift 2.0

    if let foundIndex = bombsOnScreen.indexOf( bomb)
    {
            bombsOnScreen.removeAtIndex(foundIndex)
    }

    Tags: 

    Delegate pattern

    delegation pattern

    protocol ClassDelegate: class{
      func b1Pressed()
     
    }


    class Class: UIView
    {

      weak var delegate: ClassDelegate?
    ...
    func b1action(sender:UIButton)
      {
        self.delegate?. b1Pressed()
      }


    class ViewController: UIViewController, ClassDelegate {

      override func viewDidLoad() {
        super.viewDidLoad()
        let class = Class(frame: CGRectMake(0, 0, 234, 234))
        menu.delegate = self
    ...

      }

    ...
      func b1Pressed() {
        println("clc")
      }
    ...

    Tags: 

    Audio in ViewController

    import Foundation
    import AVFoundation
    import UIKit

    class AudioPlayerHelper {
     
      static func setupAudioPlayerWithFile(file: String, type:String)-> AVAudioPlayer?
      {
       
        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        let url = NSURL.fileURLWithPath(path!)
        do{
          let audioplayer = try AVAudioPlayer(contentsOfURL: url)
          return audioplayer
        }
        catch{
          return nil
        }
      
       
      }
    }

    import UIKit
    import AVFoundation

    class ViewController: UIViewController {

      var click = AVAudioPlayer()
      var whistle = AVAudioPlayer()
     
      override func viewDidLoad() {
        super.viewDidLoad()
      
        whistle = AudioPlayerHelper.setupAudioPlayerWithFile("whistle", type: "wav")
        click = AudioPlayerHelper.setupAudioPlayerWithFile("click", type: "wav")
       
      }

      @IBAction func clickpressed(sender: UIButton) {
        click.play()
      }

      @IBAction func whistlePressed(sender: UIButton) {
        whistle.play()
      }
    }

    in swift 4
    import AVFoundation
    class ViewController: UIViewController {

        var buttonSoundEffect: AVAudioPlayer?
       
        override func viewDidLoad() {
            super.viewDidLoad()
           
            let path = Bundle.main.path(forResource: "button.mp3", ofType:nil)!
            let url = URL(fileURLWithPath: path)
           
            do {
                buttonSoundEffect = try AVAudioPlayer(contentsOf: url)
                buttonSoundEffect?.prepareToPlay()
            } catch {
                // couldn't load file :(
            }
        }

        @IBAction func buttonpressed(_ sender: UIButton) {
           
            buttonSoundEffect?.play()
        }
       
    }

    Tags: 

    Color Hex to Decimal and Decimal to Hex

    func colorCodeDecimalToHex(red:Int, green: Int, blue: Int) ->String
    {
      var result = ""
     
      if red >= 0 && green >= 0 && blue >= 0 &&
      red <= 255 && green <= 255 && blue <= 255
      {
        result = "0x"
        result += NSString(format:"%2X", red) as String
        result += NSString(format:"%2X", green) as String
        result += NSString(format:"%2X", blue) as String
        return result.stringByReplacingOccurrencesOfString(" ", withString: "0")
       
      }
     
      return result
    }

    func colorCodeHexToRGB(hexString: String)-> String
    {
      var result = ""
      var input = hexString.stringByReplacingOccurrencesOfString("0x", withString: "") as NSString
     
      var red = UInt8(strtoul(input.substringWithRange(NSRange(location: 0, length: 2)), nil, 16))
      var green = UInt8(strtoul(input.substringWithRange(NSRange(location: 2, length: 2)), nil, 16))
        var blue = UInt8(strtoul(input.substringWithRange(NSRange(location: 4, length: 2)), nil, 16))
     
      result = "\(red) \(green) \(blue)"
      return result
    }

    var a = colorCodeDecimalToHex(117, 186, 40) //"0x75BA28"
    var b = colorCodeHexToRGB("0x75BA28")//"117 186 40"

    Tags: 

    Pages

    Subscribe to RSS - swift