2013-11-13 3 views
0

Во-первых, я новичок в разработке ios, и я пытаюсь понять, как подойти к этому.ios append button on button press

Этот screengrab из другого приложения. При нажатии зеленой кнопки плюс он добавляет дополнительные кнопки, как один в верхней части в зависимости от того, сколько раз вы нажимаете на зеленую кнопку плюс

enter image description here

Я пытаюсь повторить это, но не знаете, с чего начать. Мой вопрос: было бы лучше создать подкласс для верхней кнопки? А потом каким-то образом добавьте эту кнопку подкласса каждый раз, когда нажата кнопка «зеленый плюс»?

+3

Рассмотрите возможность использования 'UITableView' для этого и добавление новой ячейки при каждом нажатии кнопки. – Macondo2Seattle

+0

Я пробовал использовать UITableView, но не мог заставить его работать так, как мне было нужно, когда вы нажимаете либо Time, либо Item на верхней кнопке, он меняется на UITableView, как это http://i.imgur.com/yEVBSsZ.png – RipzCurlz

ответ

1

Я хотел узнать это сам, поэтому я создал образец проекта, и вот простой учебник, как это можно сделать. Не идеально, но, может быть, вы получите основную идею, как это работает.


Создание контроллера табличного представления в построителе интерфейса. Затем добавьте кнопки и текстовые поля в прототип ячейки.

Table view controller and prototype cells


Добавить новый класс в проект, давайте назовем его с именем MyTableViewController. Установите класс контроллера табличного представления в MyTableViewController (в построителе интерфейса).

enter image description here


Установить идентификатор прототипа ячейки. Я использовал значение defaultCell.

enter image description here


значения Набор тегов для кнопок и текстовых полей.

enter image description here

Я использовал эти значения тегов:

  • Плюс кнопка: 100
  • Время кнопка: 110
  • кнопку Item: 120
  • Текст поля 1: 10
  • Текстовое поле 2: 20
  • Текстовое поле д 3: 30

MyTableViewController.h (примечание: UITableView связан, как tView переменной)

#import <UIKit/UIKit.h> 

@interface MyTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> 

/* Data array */ 
@property (nonatomic) NSMutableArray *data; 
/* Expanded cell */ 
@property (nonatomic) NSInteger expandedCell; 

/* Table view */ 
@property (strong, nonatomic) IBOutlet UITableView *tView; 

@end 

MyTableViewController.m

#import "MyTableViewController.h" 

@interface MyTableViewController() 

@end 

@implementation MyTableViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    /* No cells expanded by default */ 
    _expandedCell = -1; 

    /* Create data array */ 
    _data = [NSMutableArray new]; 

    /* Add two cells to data array */ 
    UITableViewCell *cell = [self newDefaultCell:0]; 
    [_data addObject:cell]; 
    UITableViewCell *cell2 = [self newDefaultCell:1]; 
    [_data addObject:cell2]; 
} 

- (UITableViewCell *)newDefaultCell:(NSUInteger)index { 

    /* Initialize new UITableViewCell using prototype cell */ 
    UITableViewCell *cell = [_tView dequeueReusableCellWithIdentifier:@"defaultCell"]; 

    /* Initialize buttons for this cell */ 
    UIButton *plusButton = (UIButton *)[cell viewWithTag:100]; 
    [plusButton setTag:index]; 
    [plusButton addTarget:self action:@selector(plusButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    UIButton *timeButton = (UIButton *)[cell viewWithTag:110]; 
    [timeButton setTag:index]; 
    [timeButton addTarget:self action:@selector(timeButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    UIButton *itemButton = (UIButton *)[cell viewWithTag:120]; 
    [itemButton setTag:index]; 
    [itemButton addTarget:self action:@selector(itemButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    return cell; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [_data count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    /* Returns UITableViewCell object from data array */ 
    return [_data objectAtIndex:indexPath.row]; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    /* If cell is expanded, return row height 140 */ 
    if(_expandedCell == indexPath.row) { 
     return 140; 
    } /* else return row height 30 */ 
    else return 30; 
} 

- (void)plusButtonPressed:(id)sender { 
    /* Create new UITableViewCell */ 
    UITableViewCell *newCell = [self newDefaultCell:[_data count]]; 
    /* Add UITableViewCell to data array */ 
    [_data addObject:newCell]; 

    /* Update table view */ 
    [_tView beginUpdates]; 
    [_tView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:([_data count]-1)inSection:0]] withRowAnimation:UITableViewRowAnimationTop]; 
    [_tView endUpdates]; 
} 

- (void)timeButtonPressed:(id)sender { 
    UIButton *button = (UIButton*)sender; 

    /* Expand this cell to show UITextFields */ 
    _expandedCell = [button tag]; 

    /* UITableViewCell from data array, index is button's tag value */ 
    UITableViewCell *cell = [_data objectAtIndex:[button tag]]; 

    /* You can access text fields using viewWithTag: call */ 
    UITextField *tf1 = (UITextField *)[cell viewWithTag:10]; 
    UITextField *tf2 = (UITextField *)[cell viewWithTag:20]; 
    UITextField *tf3 = (UITextField *)[cell viewWithTag:30]; 

    /* Reload UITableViewRow */ 
    NSArray *indexes = @[[NSIndexPath indexPathForRow:[button tag] inSection:0]]; 
    [_tView reloadRowsAtIndexPaths:indexes withRowAnimation:UITableViewRowAnimationTop]; 
    [_tView beginUpdates]; 
    [_tView endUpdates]; 
} 

- (void)itemButtonPressed:(id)sender { 

} 

@end 

И это сделанный.

+0

Wow большое вам спасибо за это, очень полезно :) – RipzCurlz