guide developer create code apple ios objective-c ios7 uibutton autolayout

ios - developer - programmatically constraints swift 4



Ancho dinĂ¡mico UIButton usando autolayout (4)

Prueba esto

CGSize maxSize = CGSizeMake(btn.bounds.size.width, CGFLOAT_MAX); CGSize textSize1 = [btn.titleLabel.text sizeWithFont:btn.titleLabel.font constrainedToSize:maxSize]; btn.frame=CGSizeMake(10,10,textSize1.width,30);

Tengo un botón que tiene dos textos diferentes en el estado seleccionado y en el estado normal. Cuando cambio el estado del botón programaticamente no se cambia el tamaño del botón para que el texto no se muestre correctamente, ¿cuál es la mejor manera de hacerlo con el autolayout?

Conozco una forma de establecer la salida a la restricción de ancho de UIButton y cambiarla manualmente, pero estoy buscando una mejor manera


Puede usar un botón predeterminado como este:

UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTranslatesAutoresizingMaskIntoConstraints:NO]; [button setTitle:@"Normal" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; [button setTitle:@"Selected" forState:UIControlStateSelected]; [self.view addSubview:button]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[button]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[button]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)]];

Si usa un botón personalizado, entonces la manera más fácil que puedo pensar es en la subclase UIButton y agregue su UILabel personalizada dentro. Aquí está mi código corto de lo que quiero decir:

@interface CustomButton : UIButton { NSString* _normalTitle; NSString* _selectedTitle; } @property UILabel* customLabel; @end @implementation CustomButton @synthesize customLabel=_customLabel; - (instancetype)init; { self = [super init]; if ( self ) { [self setBackgroundColor:[UIColor greenColor]]; _customLabel = [UILabel new]; [_customLabel setTextColor:[UIColor whiteColor]]; [_customLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; [self addSubview:_customLabel]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_customLabel]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_customLabel)]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_customLabel]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_customLabel)]]; } return self; } - (void)setTitle:(NSString *)title forState:(UIControlState)state; { if ( state == UIControlStateNormal ) { _normalTitle = title; } else if ( state == UIControlStateSelected ) { _selectedTitle = title; } [self setSelected:[self isSelected]]; } - (void)setSelected:(BOOL)selected; { [super setSelected:selected]; if ( selected ) { [_customLabel setText:_selectedTitle]; } else { [_customLabel setText:_normalTitle]; } } @end


Cuando crea restricciones, asígnelo a variables

@property (nonatomic, strong)NSLayoutConstraint *viewConstraintTop; self.viewConstraintTop = [Your Constraint];//Initial state

Al presionar el botón, verifique si está seleccionado o no. Elimine las restricciones y vuelva a aplicar las restricciones apropiadas.

[self.viewConstraintTop autoRemove]; self.viewConstraintTop = [Your Constraint];


Simplemente diciendo [button invalidateIntrinsicContentSize]; , debería hacer lo que esperas que haga.