Swiftでボタン(UIButton)をコードで追加する

calendar

スポンサーリンク

SwiftでUIButton(テキスト設定)を追加

// UIButtonを生成
let textButton  = UIButton()
textButton.frame = CGRect(x: 100, y: 100, width: 80, height: 30)
// UIButtonにテキストを設定
textButton.setTitle("ボタン", for: UIControl.State.normal)
// UIButtonのテキストフォントを設定
textButton.titleLabel!.font = UIFont(name: "HiraKakuProN-W6",size: 14)
// UIButtonのテキストカラーを設定
textButton.setTitleColor(UIColor.black, for: UIControl.State.normal)
// UIButtonの背景色を設定
textButton.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
// UIButtonが押された時に呼び出すメソッドの設定
textButton.addTarget(self, action: #selector(tapTextButton(_:)), for: UIControl.Event.touchUpInside)
// UIButtonを追加
self.view.addSubview(textButton)
UIButton(テキスト設定)が押された時に呼び出されるメソッド
// UIButtonが押された時に呼び出されるメソッド
@objc func tapTextButton(_ sender:UIButton) {
    print("テキストボタンが押されました。")
}

SwiftでUIButton(画像設定)を追加

// UIButtonを生成
let imageButton  = UIButton(type: .custom)
imageButton.frame = CGRect(x: 200, y: 200, width: 40, height: 40);
// UIButtonに画像を設定
imageButton.setImage(UIImage(named: "buttonImage"), for: UIControl.State())
// UIButtonが押された時に呼び出すメソッドの設定
imageButton.addTarget(self, action: #selector(tapImageButton(_:)), for: UIControl.Event.touchUpInside)
// UIButtonを追加
self.view.addSubview(imageButton)
UIButton(画像設定)が押された時に呼び出されるメソッド
// UIButtonが押された時に呼び出されるメソッド
@objc func tapImageButton(_ sender:UIButton) {
    print("画像ボタンが押されました。")
}

動作環境:Xcode10.0, Swift4.2

この記事をシェアする

コメント

コメントはありません。

down コメントを残す