swiftでArrayの範囲外をよんだときにエラーにならずnilを返すextension
swiftのArrayでインデックスの範囲外を指定すると実行時にエラーになってしまう。
let data = [ 1, 2, 3, 4 ] return index < data.count ? data[index] : nil
毎度毎度こんな感じで書くのだるいので、
let data = [ 1, 2, 3, 4 ] return data[safe: index]
でアクセスできるようにする
githubではdiffを見たくないけど手元では見たい
pull-reqとか見てるとstoryboardがすごい行数のdiff出してきて他のファイルのdiffが見づらい。
そんなときは .gitattributes
に *.storyboard -diff
って追加してあげるとdiffがでなくてステキだ。
しかし、自分が作業しているときはうっかり変な変更入れていないかとか確認したいこともある。
そんなときは .git/info/attributes
に *.storyboard diff=word
って追加してあげると自分の環境だけdiffがみれてステキだ。
UICollectionViewでCellを長押ししたい
UILongPressGestureRecognizer を都度生成するの効率悪いのでViewDidLoadで一度だけ生成して、タップ後にどのCellを押したか判定する感じにする
override func viewDidLoad() { super.viewDidLoad() let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "onLongPressAction:") longPressRecognizer.allowableMovement = 10 longPressRecognizer.minimumPressDuration = 0.5 self.collectionView.addGestureRecognizer(longPressRecognizer) }
func onLongPressAction(sender: UILongPressGestureRecognizer) { let point: CGPoint = sender.locationInView(self.collectionView) let indexPath = self.collectionView.indexPathForItemAtPoint(point) if let indexPath = indexPath { switch sender.state { case .Began: // 例えばTimerをstartさせる case .Ended: // 例えばTimerをstopさせる default: break } }
AutoLayout で UIButton の image が拡大しない
UIButtonをautolayoutで配置して、画面サイズにあわせて拡縮するようにすると、UIButton自体は拡大するんだけど、そこに設定しているimage画像(UIButtonと同じサイズ、同じアスペクト比)が拡大してくれなくて困ったマン。
Alignmentをこうやればちゃんと拡大してくれるぽい。
iOS でカスタムフォントを使いたいけどなぜか表示されないとき
の通りにやったつもりだけど、なんか実機にインストールすると表示されなかった。
- フォント追加してる? -> OK
- info.plist > Fonts provided by application に追加されてる? -> NG
- Copy Budle Resourcesに追加されてる? -> NG
な感じだったので、良くわからないけど、Target > Build Phases > Copy Bundle Resources に手動で追加したフォントを入れてあげたら大丈夫になった。
storyboard で UILabel を袋文字にする
袋文字を使いたい病になった。
UIStrokeLabelみたいな感じでクラス作っておく。
import Foundation import UIKit @IBDesignable class UIDecorationLabel: UILabel { @IBInspectable var strokeSize: CGFloat = 0 @IBInspectable var strokeColor: UIColor = UIColor.clearColor() override func drawTextInRect(rect: CGRect) { // stroke let cr = UIGraphicsGetCurrentContext() let textColor = self.textColor CGContextSetLineWidth(cr, self.strokeSize) CGContextSetLineJoin(cr, kCGLineJoinRound) CGContextSetTextDrawingMode(cr, kCGTextStroke) self.textColor = self.strokeColor super.drawTextInRect(rect) CGContextSetTextDrawingMode(cr, kCGTextFill) self.textColor = textColor super.drawTextInRect(rect) } }
あとはUILabelのクラスに上のやつ設定して、適当に値を突っ込んであげればOK