iOS Autodiseño y UIToolbar/UIBarButtonItems


Tengo una vista de iOS con diseño automático habilitado y tengo un UIToolbar con un UISearchBar y UISegmentControl contenido con la barra de herramientas. Quiero que UISearchBar tenga un ancho flexible, así que necesito agregar una restricción para forzar esto, pero por lo que puedo decir, no puede agregar restricciones a los elementos en un UIToolbar en Interface Builder. Todas las opciones están deshabilitadas.

Antes AutoLayout lograría esto con autoresizingmasks.

¿No se permiten restricciones dentro de UIToolbars/UINavigationBars?

¿De qué otra manera se puede lograr esto cuando ¿usando autolayout?

Author: Dilip, 2013-02-20

3 answers

Las restricciones de diseño automático solo funcionan con UIViews y sus subclases.

Mientras que UIToolbar permite algunos elementos basados en UIView (como UISearchBar y UISegmentedControl) pueden tener que coexistir con UIBarButtonItems que no heredan de UIView.

Hasta que el diseño automático pueda funcionar con UIBarButtonItems, haz lo que has hecho.

Su alternativa es rodar su propia barra de herramientas con widgets basados solo en UIViews.

 25
Author: snorock,
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
2013-10-19 07:03:07

Esto también se puede hacer directamente desde un guion gráfico.

Simplemente arrastre y suelte elementos en la barra de herramientas y convierta algunos de ellos en espacio flexible o fijo para obtener el efecto deseado. Vea los dos ejemplos a continuación.

Espaciados uniformemente

Centrar

NB: esta es una copia de mi respuesta a Alineando elementos de UIToolbar , me tambaleé sobre ambas preguntas mientras buscaba tal solución

 9
Author: Nycen,
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-05-23 12:00:13

Puedes hacer esto en código, al menos; soy del tipo que abandona Interface Builder y lo hace en código de todos modos. IB parece interponerse en mi camino más a menudo que no cuando se trata de agregar o ajustar restricciones. Esto es lo que he hecho en mi método personalizado UIToolbar de la subclase -initWithFrame:.

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.label];

        [self addConstraint:[NSLayoutConstraint
                             constraintWithItem:self.label
                             attribute:NSLayoutAttributeCenterX
                             relatedBy:NSLayoutRelationEqual
                             toItem:self
                             attribute:NSLayoutAttributeCenterX
                             multiplier:1 constant:0]];
        [self addConstraint:[NSLayoutConstraint
                             constraintWithItem:self.label
                             attribute:NSLayoutAttributeCenterY
                             relatedBy:NSLayoutRelationEqual
                             toItem:self
                             attribute:NSLayoutAttributeCenterY
                             multiplier:1 constant:0]];
    }
    return self;
}

Y dado que me gusta cargar perezosamente tanto como sea posible, aquí está mi variable de instancia self.label (llamada cuando [self addSubview:self.label] se envía un mensaje arriba).

- (UILabel *)label {
    if (_label) return _label;
    _label = [UILabel new];
    _label.translatesAutoresizingMaskIntoConstraints = NO;
    _label.textAlignment = NSTextAlignmentCenter;
    return _label;
}

Parece funcionar para mí. No estoy agregando ningún UIBarButtonItems, sin embargo, por lo que su el kilometraje varía.

 7
Author: Ben Kreeger,
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
2013-06-19 15:32:36