0
我是比較新的雨燕,我想了一系列的動作添加到我的自定義按鈕UIView
如何將操作添加到子視圖屬性Swift?
下面的代碼,但是當過我按下按鈕,我得到這個錯誤。
請告訴我建模的最佳做法。
class CameraView: UIView {
var cameraButton : UIButton?
convenience init() {
self.init(frame: CGRectZero)
self.backgroundColor = UIColor.clearColor()
cameraButton = UIButton()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func setButton(button : UIButton){
self.cameraButton = button
}
func setUpMyView(){
self.cameraButton = UIButton()
self.cameraButton?.layer.cornerRadius = 30
self.cameraButton?.layer.borderWidth = 5
self.cameraButton?.backgroundColor = UIColor.clearColor()
self.cameraButton?.layer.borderColor = UIColor.whiteColor().CGColor
self.addSubview(cameraButton!)
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
var cameraView : CameraView?
override func viewDidLoad() {
super.viewDidLoad()
cameraView = CameraView()
cameraView?.cameraButton?.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
self.view = cameraView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pressed(sender : AnyObject!){
print("Button Pressed")
let alert = UIAlertController(title: "Alert", message: "Another Alert", preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true , completion: nil)
}
}
錯誤
2016-01-16 14:00:42.023 TPProject[4194:1442964] -[TPProject.ViewController pressed]: unrecognized selector sent to instance 0x125655a30 2016-01-16 14:00:42.028 TPProject[4194:1442964] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TPProject.ViewController pressed]: unrecognized selector sent to instance 0x125655a30' *** First throw call stack: (0x183d39900 0x1833a7f80 0x183d4061c 0x183d3d5b8 0x183c4168c 0x188a63e50 0x188a63dcc 0x188a4ba88 0x188a636e4 0x188a63314 0x188a5be30 0x188a2c4cc 0x188a2a794 0x183cf0efc 0x183cf0990 0x183cee690 0x183c1d680 0x18512c088 0x188a94d90 0x1000adf64 0x1837be8b8) libc++abi.dylib: terminating with uncaught exception of type NSException
在一個側面說明,沒有需要繼承的UIView了這一點 - 這裏看看HTTPS: //developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/。你不重寫任何UIView或UIButton的方法,所以你只需在你的ViewController中創建一個UIButton,並在ViewDidLoad()或LoadView()中配置它。如果你要重用按鈕的外觀,你可以在UIButtonExtension.swift文件中爲UIButton創建一個新的方法 - 更多https://developer.apple.com/library/ios/documentation/Swift/Conceptual/ Swift_Programming_Language/Extensions.html。 – dsieczko