2013-08-18 4 views
0

지금 당장 추가 할 버튼이있는 tableViewController가 있습니다. 버튼을 두 드리면 새 셀에 "새 습관"이라는 제목이 나타납니다. 셀을 탭하면 DetailViewController가 텍스트 필드와 함께 나타납니다. 텍스트 필드를 탭하면 UIPicker가 세 가지 옵션과 함께 표시됩니다. 첫 번째는 "자세"이고 두 번째는 "팔로 우디 아부 (Palaudies Abbs)"입니다. 세 번째 옵션은 사용자 지정입니다. 사용자 지정을 선택하면 키보드 대신 키보드가 교체됩니다. 키보드로 사용자 정의 습관을 입력하면 텍스트 필드에 표시됩니다. 자세 또는 팔라우드가 선택되면 tableViewCell의 이름이 선택 항목으로 지정됩니다 (코드에서 볼 수있는 방법). 이제 문제는 사용자 정의 옵션을 셀 제목으로 설정하는 것입니다. 현재 나는 문자열을 가져갈 수 있었고 다른 것들과 마찬가지로 삭제로 설정하려고 시도했지만 제목을 아무 것도 설정하지 않았습니다. 여기 텍스트 필드에 입력 한 내용을 기반으로 tableViewCell의 제목을 설정하십시오.

내 코드입니다

DetailViewController.h

#import <UIKit/UIKit.h> 

@protocol DetailViewDelegate <NSObject> 
- (void)setCellName2:(NSString *)cellName; 
@end 

@interface DetailViewController : UIViewController<UIPickerViewDelegate> { 
} 
@property (nonatomic, strong) id <DetailViewDelegate> delegate; 
@property (nonatomic, strong) UIToolbar *toolBar; 
@property (nonatomic, strong) UIBarButtonItem *backButton; 
@property (nonatomic, strong) UIPickerView *Picker; 
@property (nonatomic, strong) UIBarButtonItem *barDoneButton; 
@property (nonatomic, strong) UIBarButtonItem *flexSpace; 
@property (nonatomic, strong) NSString *customHabit; 
@property (nonatomic, strong) NSString *cellNames; 
@property (nonatomic, strong) IBOutlet UIBarButtonItem *doneButton; 
@property (nonatomic, strong) IBOutlet UITextField *habitField; 
- (IBAction)backToRoot:(id)sender; 
@end 

하는 .m

#import "DetailViewController.h" 

#import "HabitViewController.h" 

@interface DetailViewController() 

@property (retain, nonatomic) NSArray *pickerData; 

@end 

@implementation DetailViewController 

@synthesize Picker, toolBar, backButton, barDoneButton, flexSpace, cellNames; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.pickerData = @[@"Posture",@"Paludies Abbs",@"Custom"]; 

    toolBar = [[UIToolbar alloc] init]; 
    toolBar.barStyle = UIBarStyleBlackOpaque; 
    [toolBar sizeToFit]; 

    [toolBar setBackgroundImage:[UIImage imageNamed:@"red_navigation_bar.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault]; 

    flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                   target:self 
                   action:nil]; 
    // Done button on toolbar 
    barDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                    target:self 
                    action:@selector(releasePicker)]; 
    // Back button on toolbar 

    backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"style:UIBarButtonItemStyleDone 
               target:self 
               action:@selector(backToPicker)]; 

    // Habit PickerView 

    Picker = [[UIPickerView alloc] init]; 
    Picker.showsSelectionIndicator = YES; 
    Picker.delegate = self; 
    barDoneButton.image = [UIImage imageNamed:@"button.png"]; 

    // Toolbar above picker 

    [toolBar setItems:@[flexSpace, barDoneButton] animated:YES]; 

    self.habitField.inputAccessoryView = toolBar; 

    [self.habitField addTarget:self action:@selector(customHabitChanged) forControlEvents:UIControlEventEditingDidEnd]; 

    [self.habitField setInputView:Picker]; 

    cellNames = @"New Habit"; 

} 
- (void)customHabitChanged { 
    self.customHabit = self.habitField.text; 
    cellNames = self.customHabit; 
} 
- (void)backToPicker { 
    [toolBar setItems:@[flexSpace, barDoneButton] animated:YES]; 
    [self.habitField resignFirstResponder]; 
    [self.habitField setInputView:Picker]; 
    [self.habitField becomeFirstResponder]; 
} 
- (void)releasePicker { 
    [self.habitField resignFirstResponder]; 
    [self.habitField setInputView:Picker]; 
    [toolBar setItems:@[flexSpace, barDoneButton] animated:YES]; 
} 

- (IBAction)backToRoot:(id)sender { 
    [self.navigationController popToRootViewControllerAnimated:YES]; 
} 

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 
    return 1; 
} 


-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 
    return self.pickerData.count; 
} 


-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 
    return self.pickerData[row]; 
} 


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { 

    cellNames = [[NSString alloc] init]; 
    int select = row; 
    if (select == 0) { 
     cellNames = @"Posture"; 

     [self.delegate setCellName2:cellNames]; 

    } 
    if (select == 1) { 

     self.habitField.text = @"Palaudies Abbs"; 

     cellNames = @"Palaudies Abbs"; 


    } 
    if (select == 2) { 

     cellNames = @"Custom"; 

     [self.habitField resignFirstResponder]; 
     [self.habitField setInputView:nil]; 
     [self.habitField becomeFirstResponder]; 
     [toolBar setItems:@[backButton, flexSpace, barDoneButton] animated:YES]; 
     self.habitField.text = nil; 
     self.habitField.placeholder = @"Custom"; 
     [self.delegate setCellName2:cellNames]; 

    } 
} 

@end 

HabitViewController.h

#import <UIKit/UIKit.h> 

#import "DetailViewController.h" 

@interface HabitViewController : UITableViewController <DetailViewDelegate> { 
} 

@property (strong, nonatomic) NSIndexPath *selectedCell; 

@end 

하는 .m

#import "HabitViewController.h" 

#import "DetailViewController.h" 

@interface HabitViewController() { 
    NSMutableArray *myCells; 
} 
@property(strong, nonatomic) NSString *cellName2; 


@end 

@implementation HabitViewController 

@synthesize selectedCell; 

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

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 
    self.navigationItem.leftBarButtonItem = self.editButtonItem; 

    [self.editButtonItem setTintColor:[UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1]]; 

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; 
    self.navigationItem.rightBarButtonItem = addButton; 
    addButton.tintColor = [UIColor colorWithRed:.33 green:.33 blue:.33 alpha:1]; 

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bar.png"] forBarMetrics:UIBarMetricsDefault]; 



} 
- (void)viewDidAppear:(BOOL)animated { 

    [self.tableView reloadData]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

- (void)insertNewObject:(id)sender 
{ 
    if (!myCells) { 
     myCells = [[NSMutableArray alloc] init]; 
    } 
    [myCells insertObject:@"New Habit" atIndex:0]; 
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

#pragma mark - Table View 



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return myCells.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; 
    cell.textLabel.text = myCells[indexPath.row]; 
    return cell; 
} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [myCells removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
    } 
} 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
} 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    DetailViewController *vc = segue.destinationViewController; 
    vc.delegate = self; 
} 
#pragma mark - DetailViewDelegate 

-(void)setCellName2:(NSString *)cellName { 
    NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row; 
    NSLog(@"%@", cellName); 
    [myCells replaceObjectAtIndex:selectedRow withObject:cellName]; 
    [self.tableView reloadData]; 
} 

@end 
+0

미안하지만 나는 상당히 혼란 스럽다. "Palaudies"텍스트로 이것이 어떻게 작동하는지 보지 않고, 추가 버튼을 먼저 누르지 않고도'setCellName2 :'메소드가 어떻게 작동하는지 보지 못합니다. 코드에서 제외시킨 뭔가가 있습니까? –

+0

그곳에 있습니다. 그게 내가 가진 모든 코드입니다. 선택기 옵션을 선택하면 선택기 옵션이 전송됩니다. –

답변

0

텍스트 편집이 끝날 때보다는 시작할 때 대리자가 호출되고있는 것 같습니다. 편집이 끝날 때까지 cellName 매개 변수에는 아무런 가치가 없습니다.

사용자 정의 경우에는 텍스트 필드를 첫 번째 응답자로 설정하고 사용자가 편집을 완료 할 때 반응해야합니다.

해당 이벤트를 잡으려면 DetailVC를 텍스트 필드의 대리자로 지정하고 textFieldDidEndEditing에 응답하십시오. 이 메서드에서는 textField.text를 사용하여 대리인에게 전화를 겁니다.

+0

내가 어떻게 할 수 있는지 설명해 주시겠습니까? –

+0

위임자로 설정하고 코드가 이미 편집이 완료되면 설정되었음을 알 수 있습니다. –

관련 문제