iOS 7 Custom UINavigationBar titleView se mueve al Presionar o Hacer estallar el nuevo Controlador de vista


Estoy usando una vista de título personalizada para una UINavigationBar con el siguiente código:

// Set a label to the nav bar
THLabel *titleLabel = [[THLabel alloc] init];
titleLabel.text = @"Test";
titleLabel.font = [UIFont fontWithName:APP_FONT size:22.0];
titleLabel.frame = CGRectMake(0, 0, 100, 30);
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = CUSTOM_LIGHT_BLUE;
titleLabel.strokeColor = kStrokeColor;
titleLabel.strokeSize = kStrokeSize;
self.navigationItem.titleView = titleLabel;

El problema es que al presentar un nuevo viewcontroller y luego regresar al controlador de vista original, esta vista personalizada cambia y luego se vuelve a centrar. Por favor, vea el video para una demostración de eso.

Por favor vea el video aquí: https://www.youtube.com/watch?v=961CCVQmpJM&feature=youtu.be

He desactivado el autoresizing de cada subview para el controlador de navegación con el guion gráfico y en código para cada controlador de vista:

    // Set the navigation bar hidded on the log in view
    UINavigationController* mainViewController = (UINavigationController*)self.appDelegate.window.rootViewController;
    [mainViewController setNavigationBarHidden:YES];
    [[mainViewController navigationBar] setAutoresizesSubviews:NO];

Sin embargo, todavía cambia de tamaño! Cómo puedo detener esto - ¿qué estoy haciendo mal? ¡Gracias!

Author: PhilBot, 2014-05-04

6 answers

Es reproducible para mí solo si pongo la configuración titleView código en viewWillAppear. Moverlo a viewDidLoad soluciona el problema

 33
Author: Alex Peda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-17 10:39:48

Incrustaría la etiqueta dentro de un UIView. A Interface Builder no le gusta poner directamente un UILabel en el titleView por alguna razón que pueda estar relacionada con su problema.

También intente establecer el autoResizingMask a UIViewAutoresizingFlexibleTopMargin. En mi experiencia, cualquier vista personalizada en barras se comporta mejor de esta manera.

 4
Author: Rivera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-14 05:14:57

Esto también me pasó a mí. Hay dos cosas que puedes hacer :

1) asegúrese de que la configuración de navegación se realiza en viewDidLayoutSubviews o viewDidLoad como se mencionó en la respuesta anterior

2) tenía el elemento del botón de la barra izquierda y derecha como nil, pero solo los llamé después de que se estableció la etiqueta del título. asegúrese de establecer los elementos de los botones de la barra derecha e izquierda como nil (si no los está usando, por supuesto) antes de configurar titlelabel a titleview.

 1
Author: hellorrr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-29 05:33:11

Ampliando la respuesta de @Alex Peda anterior, estoy encontrando que en iOS7, fuera de viewDidLoad, parece haber un ancho de título mínimo para un título personalizado. Esto es lo que estoy haciendo, a continuación. Tenga en cuenta que hay algunos métodos a continuación particulares a mi código.

#define MAX_TITLE_WIDTH 400
#define MIN_TITLE_WIDTH 150

- (void) setNavBarTitle: (NSString *) newTitle;
{
    if (!newTitle) newTitle = @"";
    NSMutableString *title = [newTitle mutableCopy];

    if (![_titleView.text isEqualToString:title]) {

        NSAttributedString *attrTitle = [UIAppearance attributedString:title withFontType:FontTypeTitle | FontTypeBold | FontTypeItalic size: 40.0 andOtherAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
        _titleView.attributedText = attrTitle;
        [_titleView sizeToFit];

        // In iOS7, if you set the nav bar title with a custom view outside of viewDidLoad, there appears to be a minimum title width. Narrower custom view titles are not centered properly. I'm working around this by centering the text in the label, and setting the width of the label to the minimum width.
        if ([Utilities ios7OrLater]) {
            if (_titleView.frameWidth < MIN_TITLE_WIDTH) {
                _titleView.textAlignment = NSTextAlignmentCenter;
                _titleView.frameWidth = MIN_TITLE_WIDTH;
            }
        }

        if (_titleView.frameWidth > MAX_TITLE_WIDTH) {
            _titleView.frameWidth = MAX_TITLE_WIDTH;
        }
    }

    self.navigationItem.titleView = _titleView;
}
 0
Author: Chris Prince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-15 20:17:21

En mi caso sucedió porque estaba configurando UIBarButton antes de titleView. Configurar titleView debería ser lo primero. Ahora funciona perfectamente.

 0
Author: Michał Kwiecień,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 07:54:54

Lo que funcionó para mí fue crear una variable en el controlador de vista que contenga la vista de título deseada y luego inicializarla en viewDidLoad. Luego puede establecer esa vista en self.navigationItem.titleView en viewWillAppear y debería mostrarse correctamente. No hay necesidad de configurar autoResizeMask, o rightBarButtons, etc.

Ejemplo:

class ViewController {
    var myTitleImage: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        myTitleImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        myTitleImage.contentMode = .scaleAspectFit
        myTitleImage.image = #imageLiteral(resourceName: "my_title_image")
        // etc...
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.titleView = self.myTitleImage
    }    
}
 0
Author: Alphonsus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 04:30:37