如何在Swift中的自定义类中创建UIButton操作

时间:2016-05-28 08:42:25

标签: swift uibutton action target

我想创建一个类来添加UIButton动作,然后viewcontroller可以调用这个类来创建动作。

但错误消息告诉我"无法识别的选择器已发送到实例"

我该如何修复它们?

class MYController: UIViewController{
    @IBOutlet weak var pptMode: UIButton!
    @IBOutlet weak var videoMode: UIButton!
    @IBOutlet weak var meetingMode: UIButton!
    @IBOutlet weak var videoMeeting: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        ModeChange().modeChangeUtil(self,pptMode:pptMode, videoMode: videoMode, meetingMode: meetingMode, videoMeeting: videoMeeting)

    }
}


class ModeChange {

    func modeChangeUtil(vc:UIViewController,pptMode:UIButton,videoMode:UIButton,meetingMode:UIButton,videoMeeting:UIButton){
        pptMode.addTarget(vc, action: "modeTouched:", forControlEvents:UIControlEvents.TouchUpInside)
        pptMode.tag = modeButtonTag.ppt.rawValue

        videoMode.addTarget(vc, action: "modeTouched:", forControlEvents:UIControlEvents.TouchUpInside)
        videoMode.tag = modeButtonTag.video.rawValue
        meetingMode.addTarget(vc, action: "modeTouched:", forControlEvents:UIControlEvents.TouchUpInside)
        meetingMode.tag = modeButtonTag.meeting.rawValue
        videoMeeting.addTarget(vc, action:"modeTouched:", forControlEvents:UIControlEvents.TouchUpInside)
        videoMeeting.tag = modeButtonTag.videoMeeting.rawValue


    }
    enum modeButtonTag: Int {
        case ppt
        case video
        case meeting
        case videoMeeting
    }
   func modeTouched(sender:UIButton){
        let modeCmd:ModeCommand = ModeCommand(device: Mode(onoffUrl: OfficeConstants.MeetingRoom3A.MODE))
        switch sender.tag {
        case modeButtonTag.ppt.rawValue:
            modeCmd.modeStatus = .PPT

        case modeButtonTag.video.rawValue:
            modeCmd.modeStatus = .Video
        case modeButtonTag.meeting.rawValue:
            modeCmd.modeStatus = .Meeting
        case modeButtonTag.videoMeeting.rawValue:
            modeCmd.modeStatus = .VideoMeeting
        default: break
            //do nothing
        }
        modeCmd.execute()
    }
}

1 个答案:

答案 0 :(得分:0)

您传递了错误的参数!

addTarget方法有3个参数:

  1. target是选择器将被发送到的实例。
  2. action是一个选择器
  3. forControlEvents是您要处理的事件
  4. 在解释这些之后,您能找出代码中哪个参数错误吗?

    这是target

    由于选择器将发送到target,因此目标必须有一个名为modeTouched:的方法。

    在方法调用中,您将vc作为target传递。这意味着必须将选择器modeTouched:发送到vc。但是,您没有在modeTouched:中定义vc方法!这就是错误发生的原因。

    我想你想要将选择器发送到modeTouched:类中的ModeChange方法。因此,目标应为self

    pptMode.addTarget(self, action: #selector(modeTouched:), forControlEvents:UIControlEvents.TouchUpInside)
    

    那应该解决它!