2013-12-17 6 views
1

Я новичок в Objective-c, и я дошел до проблемы.Добавить UItextfield при нажатии кнопки

Я пытаюсь создать небольшое приложение для табло, чтобы узнать больше о языке. Вот небольшая часть приложения.

example 1

Что я хочу, это нужно сделать, это добавить новое поле UItext при нажатии на кнопку добавить. Таким образом, щелчок на кнопке выглядит так.

example 2

Как я могу добавить несколько UItextfields на кнопку мыши в Objective-C?

ответ

2

Это очень простое требование. Все, что вам нужно сделать, это создать и добавить новое текстовое поле «Player Number» и «Fouls» при каждом нажатии кнопки «Добавить». После этого переместите кнопку «Добавить» вниз и все. Вот пример кода.

Прежде всего, чтобы все было просто, я создал подкласс UIViewController, чтобы удержать текстовое поле «Номер игрока» и метку «Фолы», чтобы упростить их создание несколько раз. Вот класс:

// The .h file 
#import <UIKit/UIKit.h> 

@interface LLPlayerViewController : UIViewController 
// This is a very simple class with no public properties or methods 
@end 

// The .m file 
@implementation LLPlayerViewController 

-(void)loadView { 
    // Create the initial view 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 190, 25)]; 
    self.view = view; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // PlayerNumber Text Field 
    UITextField *playerNumberField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 120, 20)]; 
    playerNumberField.placeholder = @"PlayerNumber"; 
    playerNumberField.borderStyle = UITextBorderStyleLine; 
    [self.view addSubview:playerNumberField]; 

    // Fouls Label 
    UILabel *foulsLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, 0, 50, 20)]; 
    foulsLabel.text = @"0"; 
    [self.view addSubview:foulsLabel]; 
} 

@end 

Затем в главном View Controller я создавать экземпляры этого класса и добавить их к виду каждый раз, когда я нажимаю на кнопку «Добавить». Вот пример кода:

// Don't forget to import the previous class 
#import "LLPlayerViewController.h" 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Inside viewDidLoad add the following code: 
    self.playersArray = [[NSMutableArray alloc] init]; 

    // PLAYER Header 
    UILabel *playerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 25, 80, 20)]; 
    playerLabel.text = @"PLAYER"; 
    [self.view addSubview:playerLabel]; 

    // FOULS Header 
    UILabel *foulsLabel = [[UILabel alloc] initWithFrame:CGRectMake(145, 25, 80, 20)]; 
    foulsLabel.text = @"FOULS"; 
    [self.view addSubview:foulsLabel]; 

    // Add player button 
    self.addPlayerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    self.addPlayerButton.frame = CGRectMake(30, 60, 80, 30); 
    [self.addPlayerButton setTitle:@"Add" forState:UIControlStateNormal]; 
    [self.addPlayerButton addTarget:self action:@selector(addPlayerTapped:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:self.addPlayerButton]; 
} 

// This method will get called each time the user taps the "Add" button 
-(void)addPlayerTapped:(id)sender { 

    NSLog(@"Adding Player"); 
    self.yOffset = 60.0; 

    LLPlayerViewController *llVC = [[LLPlayerViewController alloc] init]; 
    llVC.view.alpha = 0.0; 
    [self.playersArray addObject:llVC]; 
    [self.view addSubview:llVC.view]; 

    [self repositionFields]; 
} 

// This method is responsible for repositioning the views 
-(void)repositionFields { 

    // Reposition each view in the array 
    for (LLViewController *llVC in self.playersArray) { 
     CGRect frame = llVC.view.frame; 
     frame.origin.x = 15; 
     frame.origin.y = self.yOffset; 
     llVC.view.frame = frame; 
     self.yOffset += frame.size.height; 
    } 

    // Add some animations to make it look nice 
    [UIView animateWithDuration:0.3 animations:^{ 
     CGRect frame = self.addPlayerButton.frame; 
     frame.origin.y = self.yOffset; 
     self.addPlayerButton.frame = frame; 
    } completion:^(BOOL finished) { 
     LLViewController *llVC = [self.playersArray lastObject]; 
     llVC.view.alpha = 1.0; 
    }]; 
} 

Этот код был протестирован на симуляторе iPad, но я считаю, что он также будет работать на iPhone. Код является прямым и понятным, но дайте мне знать, если у вас есть еще вопросы.

Надеюсь, это поможет!

Смежные вопросы