settitle ios objective-c fonts uibutton

ios - settitle - set title swift



UIButton no cambia el tamaño de fuente automáticamente (1)

Estoy agregando un UIButton programáticamente a mi vista, y quiero que el tamaño de fuente en el botón cambie su tamaño automáticamente (por ejemplo, si el texto es largo, redimensionarlo a una fuente más pequeña para que se ajuste al botón)

Este código no funciona (la fuente es siempre la misma):

myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal]; [myButton setFrame: CGRectMake(0, 0, 180, 80)]; [myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:16.0]]; myButton.titleLabel.adjustsFontSizeToFitWidth = TRUE; [theView addSubview:myButton];


El código funciona, pero tal vez no de la forma que usted quiere. La propiedad adjustsFontSizeToFitWidth solo reduce el tamaño de fuente si el texto no se ajusta (hasta el minimumFontSize ). Nunca aumentará el tamaño de la fuente. En este caso, un "hola" de 16 puntos encajará fácilmente en el botón ancho de 180 puntos, por lo que no se cambiará el tamaño. Si desea que la fuente aumente para adaptarse al espacio disponible, debe aumentarla a un número grande para que luego se reduzca al tamaño máximo que se ajuste.

Solo para mostrar cómo está funcionando actualmente, aquí hay un buen ejemplo creado (haga clic en el botón para reducir su ancho y ver cómo se reduce la fuente al minimumFontSize ):

- (void)viewDidLoad { [super viewDidLoad]; UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [myButton setTitle:[NSString stringWithFormat:@"hello"] forState:UIControlStateNormal]; [myButton setFrame: CGRectMake(10, 10, 300, 120)]; [myButton.titleLabel setFont: [UIFont boldSystemFontOfSize:100.0]]; myButton.titleLabel.adjustsFontSizeToFitWidth = YES; myButton.titleLabel.minimumFontSize = 40; [myButton addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:myButton]; } - (void)buttonTap:(UIButton *)button { button.frame = CGRectInset(button.frame, 10, 0); }