如何向子视图添加操作 属性 Swift



我对 Swift 比较陌生,我想在我的自定义UIView按钮中添加一系列操作

这是代码,但是当我按下按钮时,我会收到此错误。

请告诉我对此进行建模的最佳实践。

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 按下]:无法识别的选择器发送到实例0x125655a302016-01-16 14:00:42.028 TPProject[4194:1442964] *** 由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:"-[TPProject.ViewController 按下]:无法识别的选择器发送到实例0x125655a30"第一个抛出调用堆栈:(0x183d39900 0x1833a7f80 0x183d4061c 0x183d3d5b8 0x183c4168c 0x188a63e50 0x188a63dcc 0x188a4ba88 0x188a636e4 0x188a63314 0x188a5be30 0x188a2c4cc 0x188a2a794 0x183cf0efc 0x183cf0990 0x183cee690 0x183c1d680 0x18512c088 0x188a94d90 0x1000adf64 0x1837be8b8)libc++abi.dylib:以 NSException 类型的未捕获异常终止

我想出了解决方案。我不得不添加一个 : 到操作

从这条线

cameraView?.cameraButton?.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)

cameraView?.cameraButton?.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)

最新更新