2015-04-21 2 views
4

Итак, я пытаюсь сделать центральную кнопку на UINavigationBar, подобную популярной настройке UITabBar. Но у него возникла небольшая проблема.UINavigationBar titleView выше самого бара

В основном все работает хорошо, у меня есть настройка бара размером, показывающая заголовок правильно, работая с AutoLayout (topLayoutGuide). Даже анимация push работает хорошо. Но поп-анимация терпит неудачу. Это скриншоты или обрезание до границ, и я не могу найти хорошую работу, которая не заставляет меня просто хотеть создать пользовательский элемент управления и пропускать UINavigationBar.

Heres видео, показывающее, что именно происходит. http://tinypic.com/r/2vl8yl1/8

Heres некоторый код для пользовательской Панели навигации:

private let NavigationBarOffset: CGFloat = 10.0 

class ActionNavigationBar: UINavigationBar { 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     self.clipsToBounds = false 
     self.contentMode = .Redraw 

     // Slide the original navigationBar up to make room for the actionbutton 
     transform = CGAffineTransformMakeTranslation(0.0, -NavigationBarOffset) 
    } 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func sizeThatFits(size: CGSize) -> CGSize { 
     var expectedSize = super.sizeThatFits(size) 

     // Adjust the height of the navigation bar 
     expectedSize.height += NavigationBarOffset 

     return expectedSize 
    } 
} 

Вот код получает кнопку там:

navigationItem.title = "Browse" 
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Bookmarks, target: nil, action: nil) 
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "next") 

let button = UIButton() 
button.setTranslatesAutoresizingMaskIntoConstraints(false) 
button.setTitle("+", forState: .Normal) 
button.setTitle("", forState: .Highlighted) 
button.titleLabel?.font = UIFont.boldSystemFontOfSize(40.0) 
button.backgroundColor = self.view.tintColor 
button.layer.cornerRadius = 27.0 

let buttonWrapper = UIView(frame: CGRect(x: 0, y: 0, width: 60.0, height: 60.0)); 
buttonWrapper.addSubview(button) 

NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: buttonWrapper, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true 
NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: buttonWrapper, attribute: .Bottom, multiplier: 1.0, constant: 0.0).active = true 
NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 54.0).active = true 
NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 54.0).active = true 

navigationItem.titleView = buttonWrapper; 
+1

Я использовал другой подход, чтобы сделать это с помощью 'TabBar' Вместо того, чтобы ставить кнопку внутри контроллера, я поместил ее поверх нее с помощью метода' viewWillLayoutSubviews'. С их помощью вы можете добавить кнопку в качестве подсмотра представления '[self.view addSubview: centerTabButton];' – rmp

+0

Итак, в этом случае у вас есть подкласс UINavigationController? Причина, по которой я стеснялась, заключалась в том, что мне как-то придется подражать анимации push/pop. –

+1

Да, вам нужно подклассы. Правда, вам также нужно будет разработать анимацию. В нашем случае это был единственный надежный способ заставить его работать для 'TabBar', но для этого нам не пришлось иметь дело с анимацией. – rmp

ответ

2

Я попробовал следующее override func viewDidLoad(). Он отлично работает для меня, не используя настраиваемую панель навигации.

override func viewDidLoad() 
{ 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    //self.edgesForExtendedLayout = UIRectEdge.None 
    //navigationItem.title = "Browse" 

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Bookmarks, target: nil, action: nil) 
    navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "next") 



    let button = UIButton() 
    //button.setTranslatesAutoresizingMaskIntoConstraints(false) 
    button.frame = CGRectMake(0, 0, 40, 40) 
    button.setTitle("+", forState: .Normal) 
    button.setTitle("", forState: .Highlighted) 
    button.titleLabel?.font = UIFont.boldSystemFontOfSize(40.0) 
    button.backgroundColor = self.view.tintColor 
    button.layer.cornerRadius = 20 

    let buttonWrapper = UIView(frame: CGRect( 0, y: 0, width: 40, height: 40)); 
    //buttonWrapper.backgroundColor = UIColor.redColor() 
    buttonWrapper.addSubview(button) 

    /*NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: buttonWrapper, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true 
    NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: buttonWrapper, attribute: .Bottom, multiplier: 1.0, constant: 0.0).active = true 
    NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 54.0).active = true 
    NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 54.0).active = true*/ 

    navigationItem.titleView = buttonWrapper; 
} 

iPhone 6 image

+0

Ваше представление не соответствует тому, что показано в видео. Вы вообще не нарисовали кнопку за пределами UINavigationBar. –

1

Вообще UINavigationBar высота составляет 65 и она занимает около 10 YOffset, прежде чем название для StatusBar. Таким образом, U может установить ваш заголовок в пределах от 10 до 65 yOffset of NavigationBar. Максимальная высота вашей кнопки равна (65-10) = 55.

Так и есть два решения:

  1. Вы можете изменить высоту и ширину кнопки, как,

    let buttonWrapper = UIView(frame: CGRect(x: 0, y: 0, width: 45.0, height: 45.0));

  2. Или и может изменить значение YOffset кнопки, как,

    let buttonWrapper = UIView(frame: CGRect(x: 0, y: -8, width: 60.0, height: 60.0));

Смежные вопросы