14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift/iOS]StoryBoardを使わずに、UIButtonを実装する方法

Last updated at Posted at 2018-01-24

開発環境

Swift 4
Xcode 9.2

ポイント

UIButtonの追加

sample.swift
let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
button.backgroundColor = .black
button.setTitle("sample", for: .normal)
button.setTitleColor(.white, for: .normal)
self.view.addSubview(button)

UIButtonを押すと、発火するfunc

func の前に @objc を追加

sample.swift
@objc func pushButton(sender: UIButton){
        print("button pushed.")
}

UIButtonとfuncの紐付け

sample.swift
let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
button.backgroundColor = .black
button.setTitle("sample", for: .normal)
button.setTitleColor(.white, for: .normal)

//追加したコード
button.addTarget(self, action: #selector(pushButton), for: .touchUpInside)

self.view.addSubview(button)

コード例

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
        button.backgroundColor = .black
        button.setTitle("sample", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(pushButton), for: .touchUpInside)
        self.view.addSubview(button)
        
    }
    
    @objc func pushButton(sender: UIButton){
        print("button pushed.")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?