设置滚动以便以编程方式在文本框中放置文本框

时间:2014-04-15 21:39:02

标签: ios uiscrollview

对于用户将数据输入文本框的iPhone应用程序,

我需要页面在选择文本框以供用户输入时以及未打开键盘以供用户查看他们输入的内容时滚动。

使用界面生成器并覆盖滚动视图时,我无法保留或保存,以便页面实际上可以滚动。

我也希望以编程方式执行此操作。当插入到.m文件中时,这样的其他解决方案无效。

@property (weak, nonatomic) IBOutlet UIScrollView *topScrollView;
@synthesize topScrollView;

[topScrollView setFrame:CGRectMake(320, 0, 320, 65)];
[topScrollView setContentSize:CGSizeMake(500, 100)];
[topScrollView setBackgroundColor:[UIColor greenColor]];
[topScrollView setScrollEnabled:YES];
[topScrollView setShowsHorizontalScrollIndicator:YES];
[topScrollView setShowsVerticalScrollIndicator:NO];
[[self view] addSubview:topScrollView]; 

1 个答案:

答案 0 :(得分:0)

您可以在主视图顶部放置一个包含所有文本字段的UIView,并为键盘设置通知并相应地移动视图。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowWithNotification:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideWithNotification:) name:UIKeyboardWillHideNotification object:nil];

#pragma mark NSNotifications
- (void)keyboardDidShowWithNotification:(NSNotification *)aNotification
{
    const int movementDistance = ([UIScreen mainScreen].bounds.size.height == 568 ? 155 : 180);
    [UIView animateWithDuration:0.3
                      delay:0
                    options:UIViewAnimationCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     CGPoint adjust = CGPointMake(0, -movementDistance);
                     CGPoint newCenter = CGPointMake(self.loginContainer.center.x+adjust.x, self.loginContainer.center.y+adjust.y);
                     [self.loginContainer setCenter:newCenter];
                 }
                 completion:nil];
}
- (void)keyboardDidHideWithNotification:(NSNotification *)aNotification
{
    [UIView animateWithDuration:0.3
                      delay:0
                    options:UIViewAnimationCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     self.loginContainer.frame = CGRectMake(0, 0, self.loginContainer.frame.size.width, self.loginContainer.frame.size.height);
                 }
                 completion:nil];
}