2009-11-02 17 views
12

Tengo una vista en mi aplicación que tiene una serie de botones en función de la cantidad de elementos devueltos por el servidor. Entonces, si el servidor retorna, digamos 10 elementos, debe haber 10 botones y hacer clic en cada botón debe llamar a una persona diferente.UIButton personalizado para Iphone

Para el propósito anterior, creé una clase de botón personalizada derivada de UIButton.

@implementation HopitalButton 

@synthesize index; 
@synthesize button_type; 

- (id)initWithFrame:(CGRect)frame { 

    if (self = [super initWithFrame:frame]) { 
     UIImage* img = [UIImage imageNamed:@"dr_btn.png"]; 
     [img stretchableImageWithLeftCapWidth:10 topCapHeight:10]; 
     [self setBackgroundImage:img forState:UIControlStateNormal]; 
     [self setTitleColor:[UIColor colorWithRed:0.698 green:0.118 blue:0.376 alpha:1] forState:UIControlStateNormal] ; 
     [self setFont:[UIFont fontWithName:@"Helvetica Bold" size:13]]; 
     self.titleLabel.textColor = [UIColor colorWithRed:178 green:48 blue:95 alpha:1]; 
     self.adjustsImageWhenHighlighted = YES; 
    } 
    return self; 
} 

- (void)dealloc { 
    [super dealloc]; 
} 


@end 

Ahora el problema con el código anterior es que no crea botones que parecen similares a los botones creados por defecto en constructor de interfaz. Las fronteras faltan.

Y crear botones del tipo anterior por el código siguiente:

HopitalButton* hb = [[HopitalButton alloc] init]; 
    hb.button_type = @"call"; 
    hb.frame = CGRectMake(50, 50 + i * 67, 220, 40); 
    [self.scroll_view addSubview:hb]; 
    [hb setTitle:[[[self.office_full_list objectAtIndex:i] objectForKey:@"Staff" ]objectForKey:@"FullName"] forState:UIControlStateNormal]; 
    hb.index = [NSNumber numberWithInt:[self.button_items count]]; 
    [self.button_items insertObject:hb atIndex:[self.button_items count]]; 
    [hb addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

yo no estoy encontrando una manera de establecer el tipo de botón para este botón personalizado. ¿Hay alguna manera de hacerlo? ¿O hay una mejor manera de diseñar el código?

Respuesta

27

Lo que empieza con una imagen estirable con una frontera:

alt text http://grab.by/4lP

luego de hacer un botón con la imagen estirada como fondo y aplicar texto.

INDEX_OFFSET = 82753; // random 

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)]; 
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal]; 
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]]; 
[sampleButton setTag:<INDEX>+INDEX_OFFSET]; 
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal]; 
[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:sampleButton]; 

Obviamente, tendrá que ajustar el origen del marco y el tamaño para adaptarse a su aplicación, así como el blanco, el selector, y el título. Y

+0

embargo, el índice es importante para mi programa como yo uso el índice para averiguar qué botón se presiona, ya que hay más de un botón en la vista – Amal

+0

establece una etiqueta para el botón. Actualicé el código – coneybeare

+0

¿De dónde sacaste la imagen del botón rojo estirable? – bentford

2

No deberías estar llamando initWithFrame: rect en lugar de:

HopitalButton* hb = [[HopitalButton alloc] init]; 
6
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]]; 

setFont ahora es obsoleto, utilice la propiedad titleLabel.font lugar

sampleButton.titleLabel.font = [UIFont boldSystemFontOfSize:20]; 
3

puede utilizar la clase individual por encargo Botón de redondear que puede ser útil en todo el proyecto con su estilo de marco específico como se detalla a continuación

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 
@interface CustomRoundRectButton : UIButton 
@end 


#import "CustomRoundRectButton.h" 
@implementation CustomRoundRectButton 
- (void)drawRect:(CGRect)rect 
{ 
[[self layer] setMasksToBounds:YES]; 
[self.layer setCornerRadius:10.0f]; 
[self.layer setBorderColor:[UIColor grayColor].CGColor]; 
[self.layer setBorderWidth:1.0]; 
} 
@end 

En esto debe seleccionar el tipo de botón personalizado y seleccionar su clase como CustomRoundRectButton.

For Simple custom button we can use as below 

-(UIBarButtonItem*)BackButton 
{ 
UIButton*btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
[btn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal]; 
[btn setFrame:CGRectMake(0, 0, 30, 30)]; 
[btn addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside]; 
UIBarButtonItem*barBtn = [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease]; 
return barBtn; 
} 
Cuestiones relacionadas