2010-05-11 14 views
108

aquí es mi código¿es posible ajustar la posición x, y titleLabel de UIButton?

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

[btn setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; 
[btn setTitle:[NSString stringWithFormat:@"Button %d", i+1] forState:UIControlStateNormal];  
[btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
btn.titleLabel.frame = ??? 
+1

Por favor seleccione la otra respuesta para que podamos eliminar el uno muy negativo. O bien, explica por qué has hecho esto. – tchrist

+1

¿Por qué no se acepta esa respuesta? –

+0

Esto es todo lo que necesita http://stackoverflow.com/questions/18484747/uibutton-titleedgeinsets –

Respuesta

14

Derivar UIButton y poner en práctica el método siguiente:

- (CGRect)titleRectForContentRect:(CGRect)contentRect; 

Editar:

@interface PositionTitleButton : UIButton 
@property (nonatomic) CGPoint titleOrigin; 
@end 

@implementation PositionTextButton 
- (CGRect)titleRectForContentRect:(CGRect)contentRect { 
    contentRect.origin = titleOrigin; 
    return contentRect; 
} 
@end 
+0

¿me puede mostrar algún ejemplo, por favor? – RAGOpoR

+0

Gracias, esto es lo que realmente necesitaba. El centrado automático no fue suficiente. – dmzza

423
//make the buttons content appear in the top-left 
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; 
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop]; 

//move text 10 pixels down and right 
[button setTitleEdgeInsets:UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 0.0f)]; 

Y en Swift

//make the buttons content appear in the top-left 
button.contentHorizontalAlignment = .Left 
button.contentVerticalAlignment = .Top 

//move text 10 pixels down and right 
button.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 0.0, 0.0) 
+3

esta es definitivamente la mejor respuesta – greenisus

+3

Me pregunto por qué el asker eligió la otra respuesta. Este es mucho mejor. – Joshua

+4

Ni siquiera necesitaba las dos primeras líneas ... 'setTitleEdgeInsets:' fue todo lo que encontré necesario para cambiar el texto. – ArtOfWarfare

36

El forma más fácil de hacerlo visualmente es utilizar el inspector de atributos ** (aparece cuando se edita un xib/guión gráfico), estableciendo el "borde" propiedad de título, el ajuste es inserciones, a continuación, establecer la propiedad de "borde" a la imagen, y ajustar en consecuencia. Por lo general, es mejor que codificarlo, ya que es más fácil de mantener y muy visual.

Attribute inspector setting

+1

Buen consejo para cambia 'Edge' a' Title' y luego ajusta el recuadro! – Dean

Cuestiones relacionadas