我有两个视图控制器,ViewControllerA和ViewControllerB,其中ViewControllerB是ViewControllerA的子类。以下是ViewControllerA中的代码实现。
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createButton()
buttonPressed()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createButton () {
let button = UIButton();
button.setTitle("Add", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.frame = CGRectMake(200, 65, 46, 30) // X, Y, width, height
button.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonPressed(sender: UIButton!) {
var alertView = UIAlertView();
alertView.addButtonWithTitle("Done");
alertView.title = "Alert!";
alertView.message = "Button Pressed!!!";
alertView.show();
}
在我的ViewControllerB中,我想使用createButton(),但不是在ViewControllerA中使用它的方式。让我们说我想在createButton()的ViewControllerB中使用红色而不是蓝色。如何在ViewControllerB中覆盖createButton()以使其不同?
答案 0 :(得分:0)
以下方法可行。
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createButton()
buttonPressed()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createButton () {
let button = UIButton();
button.setTitle("Add", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.frame = CGRectMake(200, 65, 46, 30) // X, Y, width, height
button.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonPressed(sender: UIButton!) {
var alertView = UIAlertView();
alertView.addButtonWithTitle("Done");
alertView.title = "Alert!";
alertView.message = "Button Pressed!!!";
alertView.show();
}
class ViewControllerB: ViewControllerA {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func createButton () {
let button = UIButton();
button.setTitle("Add", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.frame = CGRectMake(200, 65, 46, 30) // X, Y, width, height
button.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
override func buttonPressed(sender: UIButton!) {
var alertView = UIAlertView();
alertView.addButtonWithTitle("Done");
alertView.title = "Alert!";
alertView.message = "Button Pressed!!!";
alertView.show();
}
希望能帮助那些也试图理解视图控制器子类化的最佳方式的人。