[gulp]gulpfile.jsテンプレ

gulpfile.jsテンプレ
https://github.com/contra/gulp-concat
https://github.com/floridoo/gulp-sourcemaps
https://github.com/floatdrop/gulp-plumber
https://github.com/mikaelbr/gulp-notify
https://github.com/dlmanning/gulp-sass
https://github.com/chilijung/gulp-cssmin
https://github.com/hparra/gulp-rename
https://github.com/terinjokes/gulp-uglify
https://github.com/hustxiaoc/gulp-minify
https://github.com/OverZealous/run-sequence

// プラグイン読み込み
var gulp         = require('gulp');
var concat       = require('gulp-concat');//ファイル結合
var sourcemaps   = require('gulp-sourcemaps');//ソースマップ出力
var plumber      = require('gulp-plumber');//エラーで処理を止めないためのプラグイン
var notify       = require('gulp-notify');//エラー時通知
var sass         = require('gulp-sass');//sass
var cssmin       = require('gulp-cssmin');//css minify
var rename       = require('gulp-rename');//ファイル名変更
var uglify       = require('gulp-uglify');//js minify&難読化
//var minify       = require('gulp-minify');
var runSequence  = require('run-sequence');//処理順序指定用

//js結合
gulp.task('js-concat', function() {
  return gulp.src(['./js.src/_intro.js',
                   './js.src/_variable.js',
                   './js.src/_common.js',
                   './js.src/_model.js',
                   './js.src/_view.article.js',
                   './js.src/_outro.js'])
    .pipe(plumber({
      errorHandler: notify.onError("Error[js-concat]: <%= error.message %>")
    }))
    .pipe(sourcemaps.init())
    .pipe(concat('script.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./js'));
});
/*
gulp.task('js-minify',function(){
  return gulp.src(['./js/script.js'])
    .pipe(minify({
      ext:{
        min:'.min.js'
      },
      compress:
    }))
    .pipe(gulp.dest('./js'));
});
*/
//js-concatの後に実行
gulp.task('js-uglify',['js-concat'], function() {
  return gulp.src(['./js/script.js'])
    .pipe(plumber({
      errorHandler: notify.onError("Error[js-uglify]: <%= error.message %>")
    }))
    .pipe(sourcemaps.init())
    .pipe(uglify({
      mangle       :false//変数名を変えない
    }))
    .pipe(rename({suffix:'.min'}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./js'));
});
gulp.task('sass', function(){
  return gulp.src('./css.src/*.scss')
    .pipe(plumber({
      errorHandler: notify.onError("Error[sass]: <%= error.message %>")
    }))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest('./css'));
});
//sassの後に実行
gulp.task('cssmin',['sass'], function(){
  return gulp.src(['./css/override.css'])
    .pipe(plumber({
      errorHandler: notify.onError("Error[cssmin]: <%= error.message %>")
    }))
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./css'));
});
// ファイルを監視して実行させる
gulp.task('watch',function() {
  return gulp.watch(['js.src/*.js','./css.src/*.scss'],['build']);
});
gulp.task('build', function(callback) {
  runSequence(['js-concat','js-uglify','sass','cssmin'],
              'watch',
              callback);
});
gulp.task('default',['build']);

concat + babel

var gulp = require("gulp");
var babel = require("gulp-babel");
var concat       = require('gulp-concat');
var plumber      = require('gulp-plumber');
var rename       = require('gulp-rename');
var notify       = require('gulp-notify');
var runSequence  = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var dir = './src/';

//結合
gulp.task('file-concat', function() {
    return gulp.src([
        dir + 'parts.intro.es6',
        dir + 'class.A.es6',
        dir + 'class.B.es6',
        dir + 'class.C.es6',
        dir + 'class.D.es6',
        dir + 'class.E.es6',
        dir + 'init.A.es6',
        dir + 'parts.outro.es6'
        ])
        .pipe(plumber({
            errorHandler: notify.onError("Error[js-concat]: <%= error.message %>")
        }))
        .pipe(concat('meter.es6'))
        .pipe(gulp.dest(dir));
});

gulp.task('babel', function() {
    return gulp.src(dir + 'result.es6')
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['es2015-ie']
        }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./'));
});

gulp.task('watch', function() {
    return gulp.watch(dir + '*.es6', ['build']);
});

gulp.task('build', function(callback) {
    return runSequence(
        'file-concat',
        'babel',
        'watch',
        callback);
});

gulp.task('default', ['build']);

[Swift]getUIColorByColorTuple

typealias rgbTuple = (r:CGFloat,g:CGFloat,b:CGFloat)

func getUIColorByColorTuple(color:rgbTuple, alpha:CGFloat=1.0, luminanceScale:CGFloat = 1.0) -> UIColor{
    var colort:rgbTuple = (r:color.r,g:color.g,b:color.b)
    let rl:CGFloat = 0.298912 * colort.r
    colort.r = rl * luminanceScale / 0.298912
    let gl:CGFloat = 0.586611 * colort.g
    colort.g = gl * luminanceScale / 0.586611
    let bl:CGFloat = 0.114478 * colort.b
    colort.b = bl * luminanceScale / 0.114478
    
    return UIColor(red: colort.r, green: colort.g, blue: colort.b, alpha: alpha)
}

[Swift]UISwitchButton

UISwitchButton

class UISwitchButton: UIButton {
    let onImage = UIImage(named: "check-on")
    let offImage = UIImage(named: "check-off")
    
    var isTapped: Bool = false {
        didSet {
            if isTapped {
                self.setImage(onImage, forState: .Normal)
            } else {
                self.setImage(offImage, forState: .Normal)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isTapped = false
        self.setImage(offImage, forState: .Normal)
        self.addTarget(self, action: #selector(UISwitchButton.tapButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override func awakeFromNib() {
        self.addTarget(self,action:#selector(UISwitchButton.tapButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.isTapped = false
    }
    func tapButton(sender: UIButton) {
        if sender == self {
            isTapped = !isTapped
        }
    }
}

[JavaScript]汎用スムーススクロール

汎用スムーススクロール

$('a[href^="#"]').click(function(e){
	var $this = $(this);
	var id = $this.attr('href').split('#').pop();
	var top = $('#'+id).offset().top;
	$('html,body').stop().animate({scrollTop:top},{duration:400});
	return false;
});

[JavaScript]get OS version

get OS version

function getiOSVersion(){
	if (/iP(hone|od|ad)/.test(navigator.userAgent)) {
		var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
		return parseInt(parseInt(v[1], 10).toString()+parseInt(v[2], 10).toString()+parseInt(v[3] || 0, 10).toString() ,10);
	}
	return 0.0;
}
function getAndroidVersion(){
	if( navigator.userAgent.indexOf("Android") > 0 ) {
		var v = navigator.userAgent.match(/Android [\d\.]+/)[0].split(' ').pop().split('.');
		return parseInt(parseInt(v[0], 10).toString()+parseInt(v[1], 10).toString()+parseInt(v[2] || 0, 10).toString() ,10);
	}
	return 0.0;
}

[Swift]UIAlertController

UIAlertController

let alertController:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction( UIAlertAction(title: cancelTitle, style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) in

} )
)
alertController.addAction( UIAlertAction(title: okTitle, style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction) in

} )
)
self.presentViewController(alertController, animated: true, completion: { 
    
})

[Swift]自作UIRefreshControl

自作UIRefreshControl

let REFRESH_HEIGHT:CGFloat = 66.0
var readyRefresh:Bool = false
var defaultInsetTop:CGFloat = 0.0

func scrollViewDidScroll(scrollView: UIScrollView) {
    if self.readyRefresh {
        if -self.REFRESH_HEIGHT < scrollView.contentInset.top + scrollView.contentOffset.y {
            self.readyRefresh = false
        }
    }else {
        if -self.REFRESH_HEIGHT >= scrollView.contentInset.top + scrollView.contentOffset.y {
            self.readyRefresh = true
        }
    }
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if !self.readyRefresh {
        return
    }
    self.readyRefresh = false
    self.defaultInsetTop = self.tableView.contentInsetTop
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.animateWithDuration(NSTimeInterval(0.3), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveLinear,
        animations: { () -> Void in
            self.tableView.contentInsetTop = self.REFRESH_HEIGHT
        },
        completion: { (finish:Bool) -> Void in
        }
    )
    
    self.executeRefresh()
}
private func endRefresh(){
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.animateWithDuration(NSTimeInterval(0.3), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveLinear,
        animations: { () -> Void in
            self.tableView.contentInsetTop = self.defaultInsetTop
        },
        completion: { (finish:Bool) -> Void in
        }
    )
}
private func executeRefresh(){
    //処理
    
    self.endRefresh()
}

[Swift]文字列分割

文字列分割

let datetimeString:String = "2016-02-17 14:51:21"
let tmp:[String] = datetimeString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:"- :"))
print(tmp)

出力結果

["2016", "02", "17", "14", "51", "21"]

[Swift]dispatch_after

dispatch_after

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    //処理
}

[Swift]UIView Extension #6

UIView Extension #6

func animateBG2Black(duration:CGFloat=0.3){
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.animateWithDuration(NSTimeInterval(duration), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveLinear,
        animations: { () -> Void in
            self.backgroundColor = UIColor.blackColor()
        },
        completion: { (finish:Bool) -> Void in
            
        }
    )
}