#ios #swift #uibutton #navigationbar
#iOS #swift #uibutton #панель навигации
Вопрос:
В моем приложении у меня есть поток, который выглядит следующим образом: пользователь нажимает кнопку, которая изменяет UIBarButtonItems, и когда пользователь нажимает на один из них, он меняется на что-то другое. Однако я получаю следующее исключение при нажатии на один из них.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.MapViewController revealLeftView]: unrecognized selector sent to instance 0x7fbc90c404c0'
Сначала кнопки, добавленные в раскадровку, получают набор действий следующим образом:
menuButton.action = #selector(PBRevealViewController.revealLeftView)
toolboxMenuButton.action = #selector(PBRevealViewController.revealRightView)
Когда пользователь нажимает на кнопку в другом месте экрана, я меняю UIBarButtons следующим образом:
let leftButton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
leftButton.setImage(UIImage(named: "close"), for: UIControlState.normal)
//add function for button
leftButton.addTarget(self, action: #selector(MapViewController.cancelAddFields), for: UIControlEvents.touchUpInside)
//set frame
leftButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let leftBarButton = UIBarButtonItem(customView: leftButton)
let rightButton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
rightButton.setImage(UIImage(named: "add"), for: UIControlState.normal)
//add function for button
rightButton.addTarget(self, action: #selector(MapViewController.confirmCreateFields(sender:)), for: UIControlEvents.touchUpInside)
//set frame
rightButton.frame = CGRect(x: 0, y: 0, width: 24, height: 20)
let rightBarButton = UIBarButtonItem(customView: rightButton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = rightBarButton
self.navigationItem.leftBarButtonItem = leftBarButton
Это работает так, как должно, и когда пользователь нажимает кнопку закрытия, я меняю UIBarButtonItems следующим образом:
let leftButton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
leftButton.setImage(UIImage(named: "MenuIcon_1"), for: UIControlState.normal)
//add function for button
//leftButton.addTarget(self, action: #selector(MapViewController.cancelAddFields), for: UIControlEvents.touchUpInside)
//set frame
leftButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
let rightButton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
rightButton.setImage(UIImage(named: "ToolsIcon_1"), for: UIControlState.normal)
//add function for button
//rightButton.addTarget(self, action: #selector(MapViewController.cancelAddFields), for: UIControlEvents.touchUpInside)
//set frame
rightButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
leftButton.addTarget(self, action: #selector(PBRevealViewController.revealLeftView), for: UIControlEvents.touchUpInside)
rightButton.addTarget(self, action: #selector(PBRevealViewController.revealRightView), for: UIControlEvents.touchUpInside)
let leftBarButton = UIBarButtonItem(customView: leftButton)
let rightBarButton = UIBarButtonItem(customView: rightButton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = rightBarButton
self.navigationItem.leftBarButtonItem = leftBarButton
Все хорошо, но когда я нажимаю на один из них, он выдает исключение, упомянутое выше. Что я делаю не так? Я пробовал .action для самого UIBarButtonItem, похоже, тоже не работает.
Комментарии:
1. в этом исключении вы можете увидеть точную строку, где это происходит, покажите нам что-нибудь еще
2. Я обновил исключение вопросов.
3. Знаете ли вы, что если вы установите
target
self
selector
значение, оно также должно быть реализовано вself
(текущем классе)?4. Интересно, ошибочен ли мой подход. В моем viewDidLoad я устанавливаю эти
menuButton.action = #selector(PBRevealViewController.revealLeftView)
иmenuButton.target = self.revealViewController()
Ответ №1:
Кажется, что в:
leftButton.addTarget(self, action: #selector(PBRevealViewController.revealLeftView), for: UIControlEvents.touchUpInside)
self
(цель) на самом деле не является экземпляром PBRevealViewController
, а MapViewController
. Это означает, что вы указываете кнопке вызвать метод revealLeftView
на a MapViewController
.
Убедитесь, что вы используете правильный target
.