Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active March 7, 2019 06:01
Show Gist options
  • Save KentarouKanno/42f1b9180fc81722b367 to your computer and use it in GitHub Desktop.
Save KentarouKanno/42f1b9180fc81722b367 to your computer and use it in GitHub Desktop.
UIButton

UIButton

UIButton Class Reference
UIButton Drag & Tap
UIButton Gradient
UIButton+Extension
UIButton + UILongPressGestureRecognizer

★ ボタンの種類

public enum UIButtonType : Int {
    
    case Custom // no button type
    @available(iOS 7.0, *)
    case System // standard system button
    
    case DetailDisclosure
    case InfoLight
    case InfoDark
    case ContactAdd
}

★ ボタンの生成

let mybutton = UIButton()
        
let button: UIButton = UIButton()
        
let infoDarkButton: UIButton = UIButton(type: UIButtonType.InfoDark)

let addButton: UIButton = UIButton(type: .ContactAdd)

★ ボタンのサイズを設定

button.frame = CGRectMake(50, 50, 300, 50)

★ ボタンの中心位置を設定

button.layer.position = CGPoint(x:150, y:75)

button.center =  CGPoint(x:150, y:75)

★ ボタンの背景色を設定

// (UIView)
button.backgroundColor = UIColor.yellowColor()

★ ボタンのタイトルを設定

button.setTitle("Tap Me!", forState: .Normal)

★ ボタンタップ時のタイトルを設定

button.setTitle("Tapped!", forState: .Highlighted)

★ ボタンのタイトルカラーを設定

button.setTitleColor(UIColor.blueColor(), forState: .Normal)

★ ボタンタップ時のタイトルカラーを設定

button.setTitleColor(UIColor.redColor(), forState: .Highlighted)

★ ボタンにタグ番号を設定する

button.tag = 1

★ ボタン押下時中心をハイライトさせるかの設定

// ハイライトする
button.showsTouchWhenHighlighted = true
        
// ハイライトしない Default
button.showsTouchWhenHighlighted = false

★ ボタンの角丸を設定

button.layer.cornerRadius = 10.0

★ ボタン周りのボーダーの幅を設定

// Defaultは黒色
button.layer.borderWidth = 1.0

★ ボタン周りのボーダーのカラーを設定

button.layer.borderColor = UIColor.greenColor().CGColor

★ ボタン画像を設定する

let image = UIImage(named: "image.png")
button.setImage(image, forState:.Normal)

★ ボタンタップ時の画像を設定する

let image = UIImage(named: "image.png")
button.setImage(image, forState:.Highlighted)

★ ボタンの背景画像を設定する

let backImage = UIImage(named: "back.png")
button.setBackgroundImage(backImage, forState: .Normal)

★ ボタンタップ時の背景画像を設定する

let backImage = UIImage(named: "back.png")
button.setBackgroundImage(backImage, forState: .Highlighted)

★ ボタンのタイトルを取得する

var title = button.currentTitle

★ ボタンタイトルのカラーを取得する

var color = button.currentTitleColor

★ ボタンの画像を取得する

var image = button.currentImage

★ ボタンの背景画像を取得する

var backImage = button.currentBackgroundImage

★ ボタンタイトルのフォントを設定する

button.titleLabel?.font = UIFont.systemFontOfSize(20)

★ ボタンの有効、無効を設定する

// ボタンを押せるようにする(有効化)
button.enabled = true

// ボタンを押せなくする(無効化)
button.enabled = false

★ ボタンタイトルの位置を調整する

button.titleEdgeInsets = UIEdgeInsetsMake(20 ,20 ,0 ,0)
// UIEdgeInsetsMake(top, left, bottom, right)

★ ボタンのコンテンツの位置を調整する

button.contentEdgeInsets = UIEdgeInsetsMake(80 ,50 ,0 ,0)
// UIEdgeInsetsMake(top, left, bottom, right)

★ ボタンのイメージの位置を調整する

button.imageEdgeInsets = UIEdgeInsetsMake(50 ,20 ,0 ,0)
// UIEdgeInsetsMake(top, left, bottom, right)

★ ボタンタイトルの横位置を調整する

// (UIControl)
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left

/*
UIControlContentHorizontalAlignment.Center
UIControlContentHorizontalAlignment.Left
UIControlContentHorizontalAlignment.Right
UIControlContentHorizontalAlignment.Fill
*/

★ ボタンタイトルの縦位置を調整する

// (UIControl)
button.contentVerticalAlignment = UIControlContentVerticalAlignment.Top

/*
UIControlContentVerticalAlignment.Top
UIControlContentVerticalAlignment.Center
UIControlContentVerticalAlignment.Bottom
UIControlContentVerticalAlignment.Fill
*/

★ ボタンをタップ時に実行するメソッドを指定

// 引数なし
button.addTarget(self, action: #selector(ViewController.tapped), forControlEvents: .TouchUpInside)

// Selectorを定義して設定
let sel = #selector(ViewController.doSomething)
button.addTarget(self, action: sel, forControlEvents: .TouchUpInside)

func tapped() {
    print("Tapped!")
}

// 引数 UIButton
button.addTarget(self, action: "tapped:", forControlEvents:.TouchUpInside)

func tapped(button :UIButton) {
    print("Tapped!\(button.tag)")
}

// 引数 UIButton, UIEvent
button.addTarget(self, action: "tapped:event:", forControlEvents: .TouchUpInside)

func tapped(button :UIButton, event: UIEvent) {
    
    print("Tapped!\(button)")
    // <UIButton: 0x7fd5a8666c60; frame = (100 100; 100 100); opaque = NO; tag = 999; layer = <CALayer: 0x7fd5a8664b80>>
    
    print("Tapped!\(event)")
    // <UITouchesEvent: 0x7fd5a8508420> timestamp: 13911.3 touches: {(
    // <UITouch: 0x7fd5a854a860> phase: Ended tap count: 1 window: <UIWindow: 0x7fd5a87d7450; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x7fd5a873ebe0>; layer = <UIWindowLayer: 0x7fd5a87d66f0>> view: <UIButton: 0x7fd5a8666c60; frame = (100 100; 100 100); opaque = NO; tag = 999; layer = <CALayer: 0x7fd5a8664b80>> location in window: {158, 170.66665649414062} previous location in window: {158, 170.66665649414062} location in view: {58, 70.666656494140625} previous location in view: {58, 70.666656494140625}
)}
    
}

★ タイトル文字が表示領域を超えた場合の処理を設定する

// minimumScaleFactorの設定がある場合はそのサイズまで縮小、ない場合は入るまで縮小される
button.titleLabel?.adjustsFontSizeToFitWidth = true
        
// フォントを縮小しない、入らない時は3点リーダー表示になる(Default)
button.titleLabel?.adjustsFontSizeToFitWidth = false


 タイトルの最小フォントサイスを割合で設定する

// fontSizeの50% (0.0 〜 1.0)
button.titleLabel?.minimumScaleFactor = 0.5
        
// 最小のフォントサイズ / 現在のフォントサイズ
button.titleLabel?.minimumScaleFactor = 10.0 / 15.0

★ Viewにボタンを追加する

self.view.addSubview(button)

★ Viewからボタンを取り除く

button.removeFromSuperview()

★ リサイザブルな画像を設定する

// ボタンに設定する画像を取得
var buttonImage: UIImage = UIImage(named: "image")!
        
// リサイザブルイメージを作成
var resizableImage = buttonImage.resizableImageWithCapInsets(UIEdgeInsetsMake(20, 24, 20, 24))
/*
UIEdgeInsetsMake(top: 上から伸縮しない範囲,
                 left: 左から伸縮しない範囲, 
                 bottom: 下から伸縮しない範囲, 
                 right: 右から伸縮しない範囲)
*/
        
// ボタンの背景に設定
button.setBackgroundImage(resizableImage, forState: .Normal)

★ ButtonのImage画像のcontentModeを指定する ※BackgroundImageでは指定できない

button.setImage(UIImage(named: "swift.png"), forState: .Normal)
button.imageView?.contentMode = .ScaleAspectFit

★ TouchUpInsideのイベントで指を離した時の位置がボタン上かを判定する

@IBAction func touchUpInsideButton(sender: AnyObject, forEvent event: UIEvent) {
    
    let button = sender as! UIButton
    let touch = event.touchesForView(button)?.first
    let point = touch?.locationInView(button)
    if CGRectContainsPoint(button.bounds, point!) {
        print("ボタンの内側")
    } else {
        print("ボタンの外側")
    }
}

★ UIButtonのexclusiveTouchのデフォルト設定をTrueにする ※ コード以外で生成する場合

extension UIButton {
    override public func awakeFromNib() {
        super.awakeFromNib()
        self.exclusiveTouch = true
    }
}

★ UIButtonのisHightedのstateを@IBInspectableを使って設定する

class BackgroundHighlightedButton: UIButton {
    @IBInspectable var highlightedBackgroundColor :UIColor?
    @IBInspectable var nonHighlightedBackgroundColor :UIColor?
    override var isHighlighted :Bool {
        didSet {
            if isHighlighted {
                self.backgroundColor = highlightedBackgroundColor
            }
            else {
                self.backgroundColor = nonHighlightedBackgroundColor
            }
        }
    }
}

// isSelected

class CustomButton: UIButton {
    
    @IBInspectable var selectedBackgroundColor :UIColor?
    @IBInspectable var nonSelectedBackgroundColor :UIColor?
    
    override var isSelected :Bool {
        didSet {
            self.backgroundColor =  isSelected ? selectedBackgroundColor : nonSelectedBackgroundColor
        }
    }
}

★ ボタン押下時にタイトルを下げるカスタムボタン

import UIKit

class CustomButton: UIButton {

    override var isHighlighted: Bool {
        willSet {
            super.isHighlighted = newValue
            self.titleEdgeInsets = newValue ? UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0) : .zero
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment