<Swift5>コードのみでButtonを設置する!(コピペで使えます!)<Xcode11>
スポンサードリンク
スポンサードリンク
今回は、タイトル通りStoryBoardを使わずに、コードのみで、ボタンを設置する方法、そしてカスタマイズする方法を記述していきます。
StoryBoardも便利なのですが、やっぱり保守性等考えると、勝手が悪いので、本気の方は、storyboardは使わずに、コードでアプリ作りをしてみて下さい!
現時点(2019)で最新版です!(スイフト古い記事多すぎですw)
コピー&ペーストで使えますので、そのままコピペして、いろいろいじってみて下さい!!
import UIKit
class ViewController: UIViewController {
let screenWidth = Int(UIScreen.main.bounds.size.width)
let screenHeight = Int(UIScreen.main.bounds.size.height)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//ボタン生成
let testButton = UIButton()
//ボタンの設置位置を指定
testButton.frame = CGRect(x:screenWidth/4, y:screenHeight/2,width:screenWidth/2, height:screenHeight/5)
//ボタンに表示するテキストを指定
testButton.setTitle("テキスト", for: .normal)
//ボタンに表示するテキストのカラーを指定
testButton.setTitleColor(.white, for: .normal)
//ボタンに表示するテキストのフォント、サイズを指定
testButton.titleLabel!.font = UIFont(name: "Times New Roman",size: 30)
// testButtonのバックグラウンドカラーを設定
testButton.backgroundColor = .blue
//実際にボタンをViewに表示させる
self.view.addSubview(testButton)
//ボタンが押された時に”buttonTapped"が起動する
testButton.addTarget(self, action: #selector(buttonTapped(_:)), for: UIControl.Event.touchUpInside)
}
//ボタンがタップされた時に呼び出されるfunc
@objc func buttonTapped(_ sender: UIButton) {
print("大成功")
}
}
以上で、基本的なボタンの設定は、網羅してるか?
追加で、必要な機能があれば、コメントに残して下さい!!