我想创建一个类来添加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()
}
}
答案 0 :(得分:0)
您传递了错误的参数!
addTarget
方法有3个参数:
target
是选择器将被发送到的实例。action
是一个选择器forControlEvents
是您要处理的事件在解释这些之后,您能找出代码中哪个参数错误吗?
这是target
!
由于选择器将发送到target
,因此目标必须有一个名为modeTouched:
的方法。
在方法调用中,您将vc
作为target
传递。这意味着必须将选择器modeTouched:
发送到vc
。但是,您没有在modeTouched:
中定义vc
方法!这就是错误发生的原因。
我想你想要将选择器发送到modeTouched:
类中的ModeChange
方法。因此,目标应为self
:
pptMode.addTarget(self, action: #selector(modeTouched:), forControlEvents:UIControlEvents.TouchUpInside)
那应该解决它!