2016-01-16 1 views
0

Я относительно новый для Swift, и я хотел бы добавить ряд действий по моему обычаю UIView ButtonКак добавить действие к атрибутам subviews 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 

ответ

0

я понял, решение. Я должен был добавить: к действию

от этой линии

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

в

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

На стороне записки, нет необходимости в подкласс UIView для этого - иметь взгляд здесь https: //developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/. Вы не переопределяете какие-либо методы UIView или UIButton, поэтому вы просто создаете UIButton в своем ViewController и настраиваете его в ViewDidLoad() или LoadView(). Если вы собираетесь повторно использовать внешний вид кнопки, вы можете создать новый метод для UIButton в файле UIButtonExtension.swift - здесь https://developer.apple.com/library/ios/documentation/Swift/Conceptual/ Swift_Programming_Language/Extensions.html. – dsieczko

 Смежные вопросы

  • Нет связанных вопросов^_^