iPhone: Maintain visibility of form inputs – auto-scrolling views

当你开发图标或者任何有输入区域的界面,偶尔输入框再键盘弹出时会被挡住。这样用户体验不好,用户在输入时看不到他们所输入的东西。一个解决方案,是滑动整个view让编辑区域一直是可见的。

Screen shot 2010-03-25 at 20.21.31Screen shot 2010-03-25 at 20.21.41Screen shot 2010-03-25 at 20.32.47

 

我提供的整个解决方案对UIView添加了一些方法(我知道,添加类别到cocoa的类是顽皮的)这将决定基于整个屏幕的输入位置滑动视图的多少,还有和键盘弹起一样的速度滑动视图。在编辑完成时滑动回到原来的位置。

做到这样很简单,这是我如何通过计算来滚动视图:

- (void) maintainVisibityOfControl:(UIControl *)control offset:(float)offset {
	static const float deviceHeight = 480;
	static const float keyboardHeight = 216;
	static const float gap = 5; //gap between the top of keyboard and the control

	//Find the controls absolute position in the 320*480 window - it could be nested in other views
	CGPoint absolute = [control.superview convertPoint:control.frame.origin toView:nil];

	//If it would be hidden behind the keyboard....
	if (absolute.y > (keyboardHeight + gap)) {
		//Shift the view
		float shiftBy = (deviceHeight - absolute.y) - (deviceHeight - keyboardHeight - gap - offset);
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.3f]; //this is speed of keyboard
		CGAffineTransform slideTransform = CGAffineTransformMakeTranslation(0.0, shiftBy);
		self.transform = slideTransform;
		[UIView commitAnimations];
	}
}

 

..然后我重置了视图通过使用:

- (void) resetViewToIdentityTransform {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.3f]; //this is speed of keyboard
	CGAffineTransform slideTransform = CGAffineTransformIdentity;
	self.transform = slideTransform;
	[UIView commitAnimations];
}

你只需要对你的代码做一些小的改动,并在UITextFieldDelegate调用这些方法(或其他控制代理):

- (void) textFieldDidBeginEditing:(UITextField *)textField {
	[self.view maintainVisibityOfControl:textField offset:0.0f];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	if (textField == currentControl) {
		//If the textfield is still the same one, we can reset the view animated
		[self.view resetViewToIdentityTransform];
	}else {
		//However, if the currentControl has changed - that indicates the user has
		//gone into another control - so don't reset view, otherwise animations jump around
	}
}

这里是工程拷贝(见附件)。