を追加することができます私はここUIViewController
の概念の周りの理解の欠如があると思います。 A UIViewController
は、ユーザーに表示されるビューを管理するために使用され、そのアプリケーションの1つの画面として考えることができます。他のビューコントローラにビューコントローラを埋め込むことはできますが、通常は基本的な操作のためにこれを行う必要はありません。
UIViewController
はあなたがここに詳細を見つけることができ、ライフサイクルがあります。今、あなたがやりたいようにそれが表示されるものhttps://developer.apple.com/reference/uikit/uiviewcontroller#1652793
がボタンを作成する機能をラップすることで、あなたが作成することによってこれを行うことができますファクトリメソッドViewController
クラス(または他のクラスの他のクラス)、またはUIButtonをサブクラス化し、必要なプロパティを持つボタンを作成する便利な初期化メソッドを作成します(Swift拡張も使用できますが、ここでは取り上げません) 。
が最も簡単な方法を見て、あなたのViewController
クラス内ファクトリメソッドを作成することができます:
// The button method takes a title and a selector (the selector is the method that should be called when the button is tapped)
func makeButton(title: String, action: Selector) -> UIButton {
// Create a basic button with a default size
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
// Customise the button with your settings
button.backgroundColor = .green
button.setTitle(title, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
// Return the newly created button
return button
}
は、今、私たちは、デフォルトのサイズと位置のボタンを作成する方法を持って、我々はにそのメソッドを呼び出したいですボタンを作成してViewController
のビューのサブビューとして追加します。我々は上書きviewDidLoad()
方法で何かを行うことができますことを実行するために:私たちはこのようになりますクラスを持つようにすべて一緒にそれを置くことができる方法で起こっていただきました
override func viewDidLoad() {
// Always remember to call the super method to ensure all super classes have a chance to do any work thats required by them
super.viewDidLoad()
// Create the button by calling our new method
let button = self.makeButton(title: "Test Button", action: #selector(buttonTapped))
// Set the origin of the button to move it to the right position
button.frame.origin = CGPoint(x: 100, y: 100)
// Finally add the new button as a subclass of the view controllers view
self.view.addSubview(button)
}
今、私たちは理解して:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = self.makeButton(title: "Test Button", action: #selector(buttonTapped))
button.frame.origin = CGPoint(x: 100, y: 100)
self.view.addSubview(button)
}
func makeButton(title: String, action: Selector) -> UIButton {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle(title, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
func buttonTapped(sender: UIButton) {
print("Button tapped")
}
}
を
viewDidLoadでレンダークラスの新しいインスタンスを作成しています。ビュー階層にすでに追加されているものを使用する必要があります。 –