2013-10-28 5 views
1

Я пытаюсь показать список комментариев, используя subview. Я добавил subview в self.view, и я добавил tableview к нему, чтобы показать список комментариев. теперь я хочу, чтобы пользователь добавил комментарий, я попытался добавить еще один подзаголовок к первому с текстовым полем и кнопкой в ​​нижней части экрана, но теперь я хочу переместить это представление вверх, когда клавиатура появится, а затем вернется внизу при отправке комментария, я попытался изменить рамки commentView, когда textfieldBeginEditing, но это не меняется! мой способ не работает, есть ли у вас идея делать то, что я хочу?Перемещение subview при появлении клавиатуры

благодаря

это то, что я делаю, вид называется MyView является то, что я хочу двигаться вверх:

CGRect screenRect = [[UIScreen mainScreen] bounds]; 
CGFloat screenWidth = screenRect.size.width; 
CGFloat screenHeight = screenRect.size.height; 

// notification button 
myView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth,screenHeight)]; 
[myView setBackgroundColor:[UIColor whiteColor]]; 
[myView setTag:2013]; 

commentView = [[UIView alloc] initWithFrame:CGRectMake(0,screenHeight-70,screenWidth,70)]; 
[commentView setBackgroundColor:[UIColor redColor]]; 
// [commentView viewWithTag:2031]; 

table = [[UITableView alloc] initWithFrame:CGRectMake(0,50, screenWidth, screenHeight-100)];; 
table.dataSource=self; 
table.delegate=self; 

UILabel *currentdate = [[UILabel alloc] initWithFrame:CGRectMake(0,10,screenWidth-40,50)]; 
currentdate.backgroundColor = [UIColor clearColor]; 
[currentdate setTextColor: [UIColor blueColor]]; 
[currentdate setText:@"Comments"]; 
currentdate.textAlignment= UITextAlignmentCenter; 
currentdate.font = [UIFont fontWithName:@"Helvetica" size:20.0]; 


commentFeild = [[UITextField alloc] initWithFrame:CGRectMake(60,10,screenWidth-60,30)]; 

[email protected]"add comment"; 
commentFeild.backgroundColor = [UIColor whiteColor]; 
[commentFeild setTextColor: [UIColor blueColor]]; 
commentFeild.textAlignment= UITextAlignmentRight; 
commentFeild.font = [UIFont fontWithName:@"Helvetica" size:15.0]; 
[commentFeild.layer setCornerRadius:14.0f]; 
[commentFeild setTag:2113]; 
//[commentFeild setDelegate:self]; 

UIButton *doneBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
doneBtn.frame = CGRectMake(screenWidth-45, 10,40, 30); 
doneBtn.backgroundColor = [ UIColor clearColor]; 
[doneBtn setTitle:@"done" forState:UIControlStateNormal]; 
[doneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
[doneBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside]; 

UIButton *add=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
add.frame = CGRectMake(5,10,50,30); 
add.backgroundColor = [ UIColor clearColor]; 
[add setTitle:@"add" forState:UIControlStateNormal]; 
[add setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
[add addTarget:self action:@selector(addComment) forControlEvents:UIControlEventTouchUpInside]; 

if(![taskObject.status isEqualToString:@"doneTask"]) 
{ 
    [commentView addSubview:commentFeild]; 
    [commentView addSubview:add]; 
} 

[myView addSubview:doneBtn]; 
[myView addSubview:currentdate]; 
[myView addSubview:table]; 
[myView addSubview:commentView]; 

[self.view addSubview:myView]; 
+0

вставить код, который не работает для вас –

+0

Если вы обеспечиваете эту точку зрения с помощью представления таблицы (UITableViewCell), а не добавление в качестве subview это будет легко для вас. Tableview уже занимается настройкой кадра, добавляя слушателей клавиатуры. Тем не менее, если вы хотите добавить только подвью, вам нужно добавить scrollview, соединить соответствующие делегаты и добавить представление комментариев в подвью. В текстовом файле начнется редактирование, вы должны соответственно установить смещение содержимого подвью. Надеюсь это поможет. –

+0

добавление текстового поля в представление таблицы показывает его в последней строке и о необходимости его отображения. – etab

ответ

0

я думал, что вы хотите переместить табличное представление, услышать треску е вашего модифицированного один


 @interface ViewController ( <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate> 
    { 
     BOOL KeyboardShown; 
    } 

    @end 

    @implementation ViewController 

    - (void)viewDidLoad 
    { 
    [super viewDidLoad]; 
    KeyboardShown = NO; 

// Do any additional setup after loading the view, typically from a nib. 
    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 
    CGFloat screenHeight = screenRect.size.height; 

// notification button 

    UIView *myView,*commentView; 

    myView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth,screenHeight)]; 
    [myView setBackgroundColor:[UIColor whiteColor]]; 
    [myView setTag:2013]; 

    commentView = [[UIView alloc] initWithFrame:CGRectMake(0,screenHeight-70,screenWidth,70)]; 
    [commentView setBackgroundColor:[UIColor redColor]]; 
// [commentView viewWithTag:2031]; 

    UITableView *table; 
    table = [[UITableView alloc] initWithFrame:CGRectMake(0,50, screenWidth, screenHeight-100)];; 
    table.dataSource=self; 
    table.delegate=self; 
    table.tag = 12345; 

    UILabel *currentdate = [[UILabel alloc] initWithFrame:CGRectMake(0,10,screenWidth-40,50)]; 
    currentdate.backgroundColor = [UIColor clearColor]; 
    [currentdate setTextColor: [UIColor blueColor]]; 
    [currentdate setText:@"Comments"]; 
    currentdate.textAlignment= NSTextAlignmentCenter; 
    currentdate.font = [UIFont fontWithName:@"Helvetica" size:20.0]; 


    UITextField *commentFeild = [[UITextField alloc] initWithFrame:CGRectMake(60,10,screenWidth-60,30)]; 

    [email protected]"add comment"; 
    commentFeild.backgroundColor = [UIColor whiteColor]; 
    [commentFeild setTextColor: [UIColor blueColor]]; 
    commentFeild.textAlignment= NSTextAlignmentRight; 
    commentFeild.font = [UIFont fontWithName:@"Helvetica" size:15.0]; 
    [commentFeild.layer setCornerRadius:14.0f]; 
    [commentFeild setTag:2113]; 
    commentFeild.delegate = self; 
    //[commentFeild setDelegate:self]; 

    UIButton *doneBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    doneBtn.frame = CGRectMake(screenWidth-45, 10,40, 30); 
    doneBtn.backgroundColor = [ UIColor clearColor]; 
    [doneBtn setTitle:@"done" forState:UIControlStateNormal]; 
    [doneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
    [doneBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside]; 

    UIButton *add=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    add.frame = CGRectMake(5,10,50,30); 
    add.backgroundColor = [ UIColor clearColor]; 
    [add setTitle:@"add" forState:UIControlStateNormal]; 
    [add setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
    [add addTarget:self action:@selector(addComment)  forControlEvents:UIControlEventTouchUpInside]; 


    // if(![taskObject.status isEqualToString:@"doneTask"]) 
    // { 
    //  [commentView addSubview:commentFeild]; 
    //  [commentView addSubview:add]; 
    // } 

[myView addSubview:doneBtn]; 
[myView addSubview:currentdate]; 
[myView addSubview:table]; 
[myView addSubview:commentView]; 
[commentView addSubview:commentFeild]; 
[self.view addSubview:myView]; 

} 

    - (void)viewDidAppear:(BOOL)animated 
    { 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil]; 
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidDisappear:) name:UIKeyboardDidHideNotification object:nil]; 
    } 

    - (void)viewDidDisappear:(BOOL)animated 
    { 
     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil]; 
    } 





- (void)didReceiveMemoryWarning 
    { 
     [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
    } 

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

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
     { 
     UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 

     cell.textLabel.text = @"hello"; 
     return cell; 


    } 

    - (void)keyboardDidShow:(NSNotification *)notification 
    { 
     //UIView *containerView = [self.view viewWithTag:2013]; comment this and get tableview by TAG 
     UITableView *tableView = (UITableView *)[self.view viewWithTag:12345]; 
     UIView *commentView = [self.view viewWithTag:1000];//i changed the tag and see u missed the tag for this view in viewDisLoad method check it once 


    if(!KeyboardShown) 
    { 
     KeyboardShown = YES; 
     NSLog(@"KeyBoard appeared"); 
     NSDictionary *info=[notification userInfo]; 
     NSValue *aValue=[info objectForKey:UIKeyboardFrameEndUserInfoKey]; 

     CGRect keyBoardRect=[aValue CGRectValue]; 
     keyBoardRect=[self.view convertRect:keyBoardRect fromView:nil]; 
     CGFloat keyBoardTop=keyBoardRect.origin.y; //i am getting the height of the keyboard 


     CGRect commentViewRect = commentView.frame; 
     commentViewRect.origin.y = keyBoardTop - 70; //it is the height of comment view 

     CGRect tableRect = tableView.frame; 
     tableRect.size.height = tableRect.size.height - keyBoardTop + 77;//adjust the height 



     [UIView animateWithDuration:0.2 animations:^{ 
     tableView.frame = tableRect; 
     commentView.frame = commentViewRect; 

    }]; 



    } 


} 




    - (void)keyboardDidDisappear:(NSNotification *)notification 
    { 

    // UIView *containerView = [self.view viewWithTag:2013]; //comment this 
    //dong same as above , ressetting the same as above 
    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 
    CGFloat screenHeight = screenRect.size.height; 

    UITableView *tableView = (UITableView *)[self.view viewWithTag:12345]; 
    UIView *commentView = [self.view viewWithTag:1000]; 

    if(KeyboardShown) 
    { 
     KeyboardShown = NO; 
     CGRect tableRect =CGRectMake(0,50, screenWidth, screenHeight-100); 
     CGRect commentViewRect = CGRectMake(0,screenHeight-70,screenWidth,70); 


     [UIView animateWithDuration:0.2 animations:^{ 
     tableView.frame = tableRect; 
     commentView.frame = commentViewRect; 

     }]; 
    } 
    } 









- (BOOL)textFieldShouldReturn:(UITextField *)textField 
    { 
     [textField resignFirstResponder]; 
     return YES; 
    } 

@end 


+0

попробуйте это в новом проекте и скажите мне, что он работает или нет –

+0

не начинаетсяАнимации: устарели? Я думаю + [UIView animateWithDuration: ...] является предпочтительным. – nielsbot

+0

okey выберите тот, если хотите :) Я только что продемонстрировал –

1

Я думаю, вы должны пройти через doc

+2

ничего не происходит !! – etab

+0

Да? если все произойдет? – nielsbot

+0

, если вы прочитали документы, тогда u не столкнется с какой-либо проблемой. –

2

U нужно использование уведомлений при появлении и исчезновении клавиатуры

в viewDidLoad метод Добавить это

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil]; 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidDisappear:) name:UIKeyboardDidHideNotification object:nil]; 


выше методов уволят, когда клавиатура появлялись и исчезали использовать это, чтобы внести изменения Ур Tableview

для exaple

-(void)keyboardDidShow:(NSNotification *)notification 
    { 
     NSLog(@"KeyBoard appeared"); 
     NSDictionary *info=[notification userInfo]; 
     NSValue *aValue=[info objectForKey:UIKeyboardFrameEndUserInfoKey]; 

     CGRect keyBoardRect=[aValue CGRectValue]; 
     keyBoardRect=[self.view convertRect:keyBoardRect fromView:nil]; 
     CGFloat keyBoardTop=keyBoardRect.origin.y; //i am getting the height of the keyboard 

     self.aTableView.contentInset=UIEdgeInsetsMake(0, 0, keyBoardTop+50, 0); //adjust the height by setting the "contentInset" 


    } 


когда клавиатура исчезла нравится этот


-(void)keyboardDidDisappear:(NSNotification *)notification 
    { 
     NSLog(@"KeyBoard Disappeared"); 

     [UIView beginAnimations:nil context:NULL]; 
     [UIView setAnimationDuration:0.2]; 
     self.addContactTableView.contentInset=UIEdgeInsetsMake(10, 0, 10, 0); //set to normal by setting the "contentInset" 

     [UIView commitAnimations]; 

    } 


немного работы вокруг этого у может достигнуть ваше требование

надеюсь, что это помогает u :)

+0

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

+0

ОК, затем измените кадр этого вида, когда у меня получено уведомление –

+0

Я обновил свой вопрос, вы заметили? я не могу заставить его работать – etab

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