size database

SELECT table_schema NAMEOFDB,
sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB"
FROM information_schema.TABLES GROUP BY table_schema ;

Tags: 

xcode 3.7.1 cocoapods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'testNetworkingOperation' do
    pod 'Alamofire', '~> 3.0'
     pod 'SwiftyJSON', '2.4.0'
end

Tags: 

nodejs express

npm init

npm install express --save
npm install body-parser --save
npm install nodemon --save / --g
npm install bcryptjs --save

create app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('listening on port 3000')
})

Tags: 

Symphony snips

timezone
in app kernel.php

public function __construct($environment, $debug)
{
    date_default_timezone_set('Europe/Amsterdam');
    parent::__construct($environment, $debug);
}

server:
php bin/console server:run

php bin/console generate:bundle

composer require knplabs/knp-menu-bundle dev-master

bin/console doctrine:database:create
( drop:
bin/console doctrine:database:drop --force
)

bin/console doctrine:generate:entity
bin/console doctrine:schema:update --force

Fish, bash commands as functions

make Atom.app run from terminal:

ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom

make function in Fish:
nano ~/.config/fish/functions/atom.fish

some functions:
function atom
    bash -c 'atom .'
end

function xcodeclean
        command rm -rf ~/Library/Developer/Xcode/DerivedData/*
end

function ll
    ls -lahG $argv
end

Tags: 

log vector

// log vector
for (auto const& c : numbers)
{
    std::cout << c << ' ';
}

Tags: 

Before After in collection

public extension Collection where Iterator.Element: Equatable {

public func after(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(after: idx) < endIndex else { return nil }
let nextIdx = index(after: idx)
return self[nextIdx]
}

public func before(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(before: idx) >= startIndex else { return nil }
let previousIdx = index(idx, offsetBy: -1)
return self[previousIdx]
}

public func index(before idx: Index) -> Index {
return index(idx, offsetBy: -1)
}
}

Tags: 

ZoomableGridVC

enum GridFillDirection
{
    case Horizontal, Vertical
}

class ZoomableGridViewController: UIViewController,UIScrollViewDelegate {
   
    //MARK: - Properties
   
    var scrollView: UIScrollView!
    var scrollIsZoomedIn = false
    var gridView: UIView!//Grid!//or image etc
   
    var puzzleDirection:GridFillDirection = .Horizontal
   
    var logText:UILabel!
   
    //MARK: - VC
    override func viewDidLoad() {
        super.viewDidLoad()
       
        gridView = UIImageView(image: UIImage(named: "nasa_big"))//UIView(frame: CGRectMake(0,0,view.bounds.width,view.bounds.width))//
       
        scrollView = UIScrollView(frame: CGRectMake(0,80,view.bounds.width,view.bounds.width))
        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.contentSize = gridView.bounds.size
        scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
        scrollView.delegate = self
        scrollView.maximumZoomScale = 4.0
        setZoomScale()
        scrollView.contentOffset = CGPoint(x: 0, y: 0)
        scrollView.addSubview(gridView)
        view.addSubview(scrollView)
       
        setupGestureRecognizer()
       
        setupLogText()
    }
   
    //MARK: - Setup Layout
    func setupLogText()
    {
        let logtextHeight:CGFloat = 40
        logText = UILabel(frame: CGRectMake(0,view.bounds.height-logtextHeight,view.bounds.width,logtextHeight))
        logText.textAlignment = .Center
        view.addSubview(logText)
        createLogText()
    }
   
    func createLogText()
    {
        let text = (puzzleDirection == .Horizontal) ? "Hori" :  "Verti"
        logText.text = "\(text) zoom : \(scrollView.zoomScale) "
    }
   
    func setZoomScale() {
       
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        let heightScale = scrollView.bounds.size.height / gridView.bounds.size.height
       
        scrollView.minimumZoomScale = min(widthScale, heightScale)
        scrollView.zoomScale = widthScale
    }
   
    //MARK: - ScrollView delegates
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return gridView
    }
   
    func scrollViewDidZoom(scrollView: UIScrollView) {
       
        let verticalPadding = gridView.bounds.size.height < scrollView.bounds.size.height ? (scrollView.bounds.size.height - gridView.bounds.size.height) / 2 : 0
        let horizontalPadding = gridView.bounds.size.width < scrollView.bounds.size.width ? (scrollView.bounds.size.width - gridView.bounds.size.width) / 2 : 0
       
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
       
    }
   
    //MARK: - Gestures
    func setupGestureRecognizer() {
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleDoubleTap(_:)))
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
       
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSingleTap(_:)))
        singleTap.numberOfTapsRequired = 1
        scrollView.addGestureRecognizer(singleTap)
       
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRight)
       
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeDown.direction = UISwipeGestureRecognizerDirection.Down
        self.view.addGestureRecognizer(swipeDown)
       
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        self.view.addGestureRecognizer(swipeLeft)
       
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeUp.direction = UISwipeGestureRecognizerDirection.Up
        self.view.addGestureRecognizer(swipeUp)
       
    }
   
    func handleSwipeGesture(gesture: UIGestureRecognizer) {
       
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
           
            createLogText()
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
               
                logText.text? += "Swiped right select next horizontal region"
                if swipeGesture.state == UIGestureRecognizerState.Began
                {
                   
                }
               
            case UISwipeGestureRecognizerDirection.Down:
               
                logText.text? += "Swiped down select next vertical region"
               
               
            case UISwipeGestureRecognizerDirection.Left:
               
                logText.text? += "Swiped left select previous horizontal region"
               
               
            case UISwipeGestureRecognizerDirection.Up:
               
               
                logText.text? += "Swiped up select previous vertical region"
               
               
            default:
                break
            }
        }
    }
   
    func checkZoomState()
    {
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        if widthScale == scrollView.zoomScale
        {
            //print("zoom scale full")
            scrollIsZoomedIn = false
        }
        else
        {
            //print("zoom scale zoomed")
            scrollIsZoomedIn = true
        }
    }
   
    func handleSingleTap(recognizer: UITapGestureRecognizer)
    {
        checkZoomState()
        createLogText()
        if scrollIsZoomedIn
        {
            logText.text? += "singleTap - selected cell if selected change direction"
        }
        else
        {
            logText.text? += "singleTap - selected cell "
        }
    }
   
    func handleDoubleTap(recognizer: UITapGestureRecognizer) {
        //print("double tap")
        checkZoomState()
        createLogText()
        if puzzleDirection == .Horizontal
        {
            puzzleDirection = .Vertical
        }
        else
        {
            puzzleDirection = .Horizontal
        }
    
    }
 
}

Tags: 

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 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

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: 

Pages

Subscribe to hjsnips RSS