UIGesture Tap

let tap = UITapGestureRecognizer(target: self, action: #selector({class}.{func}))
addGestureRecognizer(tap)

Tags: 

Pool

class Pool<T> {
    private var objectPool = [T]()
   
    init(items:[T]) {
        objectPool.reserveCapacity(objectPool.count)
        for item in items {
            objectPool.append(item)
        }
    }
   
    func getFromPool() -> T? {
        var result:T?
        if objectPool.count > 0 {
            result = self.objectPool.removeAtIndex(0)
        }
        return result
    }
   
    func returnToPool(item:T) {
        self.objectPool.append(item)
    }
}

Tags: 

Touch Tap

func handleSingleTap(sender:UITapGestureRecognizer){
        print("tapped")
    }
   
    func addTapGesture()
    {
        let singleTap = UITapGestureRecognizer(target:self, action:#selector(handleSingleTap))
        singleTap.numberOfTouchesRequired = 1
        singleTap.addTarget(self, action:#selector(handleSingleTap))
        view.userInteractionEnabled = true
        view.addGestureRecognizer(singleTap)
    }

or a touch view

enum Tap {
    case Single
    case Draw
    case Long
   
}

protocol HJHTouchViewDelegate: class{
    func removeSelectedFields()
    func checkThisLoc(pnt:CGPoint)
    func checkThisLocForMove(pnt:CGPoint)
    func touchEnded()
    func longpressAt(pnt:CGPoint)
    func longPressEnd()
}

class TouchView: UIView {
   
    weak var delegate: HJHTouchViewDelegate?
    var tC = 0
    var touchCells = [UIButton]()
    var startTime = NSDate()
    var longPresseTime:Double = 0.5
    var longPressTimer = NSTimer()
    var isInLongPress = false
    var isMoving = false
   
   
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        let touch = touches.first!
        tC = 0
        longPressTimer = NSTimer()
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.removeSelectedFields()
        delegate?.checkThisLoc(pnt)
        isInLongPress = false
        isMoving = false
       
        startTime = NSDate()
        longPressTimer =
            NSTimer.scheduledTimerWithTimeInterval(longPresseTime, target: self, selector: #selector(TouchView.updateTime(_:)), userInfo: [pnt.x, pnt.y], repeats: false
        )
       
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        isMoving = true
        if isInLongPress
        {
            isInLongPress = false
            delegate?.longPressEnd()
        }
        let touch = touches.first! //as! UITouch
        tC += 1
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.checkThisLocForMove(pnt)
       
    }
   
   
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        longPressTimer.invalidate()
        isInLongPress = false
       
        delegate?.touchEnded()
    }
   
    func updateTime(timer:NSTimer)
    {
        if isInLongPress ==  true || isMoving == true
        {
            return
        }
       
        if timer.userInfo != nil
        {
            if let info: AnyObject = timer.userInfo
            {
                if isInLongPress == false
                {
                    isInLongPress = true
                    var arr:[CGFloat] = info as! [CGFloat]
                    delegate?.longpressAt( CGPoint(x: arr[0],y: arr[1]))
                }
            }
        }
    }
}

Tags: 

MongoDb on rasp (notes)

on rasp
sudo /usr/bin/mongod --quiet --rest --config /etc/mongodb.conf
===
sudo nano /etc/mongodb.conf
>
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

bind_ip = 127.0.0.1,192.168.0.14
port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

in rested

http://192.168.0.14:28017/test/
POST
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/json
Accept-Language: en-us

{
"user": {
"email": "blassa4@bbbla.com",
"pwd": "test4",
"username": "test4"
}
}

base64

var str = "Hello, playground"
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)//<48656c6c 6f2c2070 6c617967 726f756e 64>

if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
   
    "Encoded:  \(base64Encoded)"//"Encoded:  SGVsbG8sIHBsYXlncm91bmQ="
   
    if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
        .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
    {
        // Convert back to a string
        "Decoded:  \(base64Decoded)"//"Decoded:  Optional(Hello, playground)"
    }
}

Tags: 

Regex

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var string = "aarde"
matchesForRegexInText("aa..e", text: string)

Tags: 

Remove Duplicates Use a Set

// Initialize the Array
var a = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates:
// first by converting to a Set
// and then back to Array
a = Array(Set(a))

print(a)

Tags: 

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

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
}

Tags: 

delete with extension

find /path . -name '*.orig' -type f -delete

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

Tags: 

rename extension

for file in *.html
do
mv "$file" "${file%.html}.txt"
done

Tags: 

print to file

history > history_for_print.txt

Tags: 

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: 

Test Webserver from raspberry pi

import smtplib
import httplib
import datetime

GMAIL_USER = 'email@gmail.com'
GMAIL_PASS = 'password'
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

def send_email(recipient, subject, text):
    smtpserver = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = 'To:' + recipient + '\n' + 'From: ' + GMAIL_USER
    header = header + '\n' + 'Subject:' + subject + '\n'
    msg = header + '\n' + text + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, recipient, msg)
    smtpserver.close()

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None  

if  get_status_code("site.com") != 200:
    f = open("/home/pi/servertest/logfile.txt", "a")
    f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' status != 200 ERROR' + '\n' )
    f.close()
    print "something wrong"
    send_email('email@gmail.com', 'server not at 200', 'server not at 200')
   
else:
    f = open("/home/pi/servertest/logfile.txt", "a")
    f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' status == 200' + '\n' )
    f.close()
    print "status == 200"

add cron to crontab
crontab -e

test every 10 minutes

*/10     *      *     *    *   python  /home/pi/servertest/servertest.py

to start cron

sudo service cron start

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)

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: 

Site Maintenance

<!doctype html>
<title>Site Maintenance</title>
<style>
  body { text-align: center; padding: 150px; }
  h1 { font-size: 50px; }
  body { font: 20px Helvetica, sans-serif; color: #333; }
  article { display: block; text-align: left; width: 650px; margin: 0 auto; }
  a { color: #dc8100; text-decoration: none; }
  a:hover { color: #333; text-decoration: none; }
</style>

<article>
    <h1>We&rsquo;ll be back soon!</h1>
    <div>
        <p>Sorry for the inconvenience but we&rsquo;re performing some maintenance at the moment. If you need to you can always <a href="mailto:">contact us</a>, otherwise we&rsquo;ll be back online shortly!</p>
        <p>&mdash; Webmaster</p>
    </div>
</article>

Tags: 

Switch Language HTML query

script.js

//switch language

$( "img" ).click(function()
{
$( "div.languageselect" ).toggle();
  var _this = $(this);
      var current = _this.attr("src");
      var swap = _this.attr("data-swap");    
     _this.attr('src', swap).attr("data-swap",current);
});

html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Switch Languages</title>
<meta name="description" content="Switch Languages">
<meta name="author" content="huh.snips.nl">
</head>

<body>

<img src="assets/images/englishflag.png" data-swap="assets/images/dutch.jpg" class="languageselect" alt="Mountain View" style="width:40px;height:22px;">
<div class="languageselect">English</div>
<div class="languageselect" style="display: none">Nederlands</div>

<script src="assets/js/jquery-2.1.3.min.js"></script>
<script src="assets/js/jquery.actual.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>

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: 

edit sites from local machine to dev server

sudo nano /etc/hosts

#server windows linux test
192.168.0.12 test.com
192.168.0.12 example.com

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: 

Pages

Subscribe to hjsnips RSS