我如何自定义导航返回按钮在iOS 7及以上没有标题?(即只使用箭头)
self.navigationItem.leftBarButtonItem = self.editButtonItem;
我只是想知道它们是否有self。backbuttonitem;
OR
像这样的东西?
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBACK
target:self action:@selector(back)];
我从iOS 5开始就一直在使用这个解决方案,没有任何问题。我在视图控制器中调用了一个实用函数。你需要在viewDidLoad或之后的任何点中做。
void updateBackButtonTextForViewController(UIViewController *viewController, NSString *text)
{
if(! viewController.navigationItem.backBarButtonItem)
{
viewController.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:text
style:UIBarButtonItemStylePlain
target:nil action:nil];
}
else
{
viewController.navigationItem.backBarButtonItem.title = text;
}
}
在某些情况下,导航项可能已经存在,在其他情况下需要创建它。这在不影响导航项标题的情况下解释了这两种情况。它允许你通过简单地传入@""来删除标题。
如果你有两个ViewController(FirstVC, seconddvc)嵌入在导航控制器中,你想在seconddvc中只有后退箭头。
你可以试试这个
在FirstVC的ViewDidLoad中
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
}
然后当你推到seconddvc,你会看到只有后退箭头
所有的答案都不能解决问题。在每个视图控制器中设置后退按钮标题,并且添加偏移量仍然会使下一个视图控制器标题向右移动,这是不可接受的。
这里是使用方法swizzling的方法,只需创建新的扩展UINavigationItem
import UIKit
extension UINavigationItem {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
// make sure this isn't a subclass
if self !== UINavigationItem.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = Selector("backBarButtonItem")
let swizzledSelector = #selector(UINavigationItem.noTitleBackBarButtonItem)
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
// MARK: - Method Swizzling
struct AssociatedKeys {
static var ArrowBackButtonKey = "noTitleArrowBackButtonKey"
}
func noTitleBackBarButtonItem() -> UIBarButtonItem? {
if let item = self.noTitleBackBarButtonItem() {
return item
}
if let item = objc_getAssociatedObject(self, &AssociatedKeys.ArrowBackButtonKey) as? UIBarButtonItem {
return item
} else {
let newItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
objc_setAssociatedObject(self, &AssociatedKeys.ArrowBackButtonKey, newItem as UIBarButtonItem?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return newItem
}
}
}