我在UINavigationBar
中设置标题和后退按钮的值,如下所示:
self.navigationItem.title = @"Post";
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [[UIColor blueColor] colorWithAlphaComponent:0.75f],
NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:20]}];
[self.navigationController.navigationBar.backItem setTitle:@"Pop Pop !"];
但是我无法在后退按钮上添加目标。我尝试过以下方法:
[self.navigationItem.backBarButtonItem setTarget:self];
[self.navigationItem.backBarButtonItem setAction:@selector(goBack:)];
和
self.navigationItem.backBarButtonItem.target = self;
self.navigationItem.backBarButtonItem.action = @selector(goBack:);
但是弹出viewController时没有调用我的选择器。
如何将目标添加到backButton,或者在弹出viewController时调用选择器? (我已经尝试了SO中提到的所有可能的解决方案,但是徒劳无功)
编辑:我更喜欢编辑股票backButton的行为,而不是将自定义按钮设置为backButton。
答案 0 :(得分:3)
我有两个解决方案,您无法在后退按钮中添加目标或操作:
1-添加一个新的barButtonItem并调用它,然后将选择器添加到它,并将其放在navigationItem.leftBarButtonItem中。别忘了弹出!
2-覆盖viewWillDisAppear方法,并做你想做的任何事情..如果你的viewcontroller没有引导你到另一个viewcontroller而是前一个...
如果您还有其他问题,请询问(Y)
答案 1 :(得分:3)
你不能将目标添加到股票BackButton,但你可以覆盖CustomNavigationController中的UINavigationBarDelegate方法,如下所示:
class CustomNavigationController: UINavigationController {
@IBOutlet weak var ibNavigationBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
ibNavigationBar.delegate = self
}
}
extension CustomNavigationController: UINavigationBarDelegate {
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
for viewController in viewControllers {
if viewController.title == "YourTitledViewController" {
popToViewController(viewController, animated: true)
}
}
return false
}
}
答案 2 :(得分:2)
您不能以这种方式更改backBarButtonItem
动作。
我在这里看到2种可能的解决方案:
要实现自定义后退按钮,请执行任何操作
以下是一个很好的解决方案,如何覆盖标准后退事件并在需要时阻止popViewController
https://github.com/onegray/UIViewController-BackButtonHandler/tree/master
答案 3 :(得分:1)
哟无法将目标添加到后退按钮。你可以添加leftbarbuttonitem和addtarget。
UIBarButtonItem *tmpButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
self.navigationItem.leftBarButtonItem = tmpButtonItem;
答案 4 :(得分:0)
首先隐藏按钮
self.navigationItem.hidesBackButton = YES;
然后你制作自定义按钮
UIButton *leftbarButton = [UIButton buttonWithType:UIButtonTypeCustom];
leftbarButton.frame =CGRectMake(70, 3, 65, 32);
[leftbarButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[leftbarButton addTarget:self action:@selector(leftbarbuttonclick) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *newdbutton =[[UIBarButtonItem alloc] leftbarButton];
将其添加到导航左栏按钮项
self.navigationItem.leftBarButtonItem =newbutton;
现在添加操作
-(void)leftbarbuttonclick {
// Your code
}
答案 5 :(得分:-1)
离开我的头顶。试试这样的事情
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(goBack:)];
tap.numberOfTapsRequired = 1;
[self.navigationItem.backBarButtonItem addGestureRecognizer:tap];