酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Swiftで角丸・背景透過・枠線のボタンを作る

メモするまでもないかもしれないけれど、こんな感じのボタンを作った。

f:id:ch3cooh393:20170225201148p:plain

Swiftで角丸背景透過枠線のみのボタンを作る

カスタムviewを使った。

import UIKit

class MyRoundButton : UIButton {
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        setTitleColor(.white, for: .normal)
        setTitleColor(.darkGray, for: [.selected, .highlighted])
        setTitleColor(.black, for: .selected)
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        tintColor = .clear
        layer.cornerRadius = frame.height / 2
        layer.borderColor = UIColor.white.cgColor
        layer.borderWidth = 2
    }
    
    override var isSelected: Bool {
        didSet {
            updateBackgroundColor()
        }
    }
    
    override var isHighlighted: Bool {
        didSet {
            updateBackgroundColor()
        }
    }
    
    fileprivate func updateBackgroundColor() {
        if !isSelected && !isHighlighted {
            backgroundColor = .clear
        } else if !isSelected && isHighlighted {
            backgroundColor = .lightGray
        } else {
            backgroundColor = .white
        }
    }
}

ボタンのテキストの変更はViewController側でおこなう。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: MyRoundButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.setTitle("ボタンですよー", for: .normal)
        button.setTitle("選択されましたー", for: .selected)
        button.setTitle("選択されましたー", for: [.highlighted, .selected])
        button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
    }
    
    func buttonAction(sender: Any) {
        button.isSelected = !button.isSelected
    }
    
}

環境

  • Xcode 8.2.1/Swift 3