前段时间做项目,遇到这样一个问题:视图控制器vc中包含一个textview,我们把VCpush出来发现textview的光标向下偏移了.....趁有时间把自己的研究成果写出来,如果哪位有不同见解也可以写出来,大家共同交流进步。下面上效果图:
代码如下:
#import "SceondViewController.h"
@interface SceondViewController ()
@end
@implementation SceondViewController
- (void)viewDidLoad {
[superviewDidLoad];
UITextView *field1 = [[UITextViewalloc]initWithFrame:CGRectMake(0,64,150, 200)];
field1.backgroundColor = [UIColorredColor];
field1.font = [UIFontsystemFontOfSize:80];
[self.viewaddSubview:field1];
self.view.backgroundColor = [UIColorwhiteColor];
}
self.navigationController.navigationBar.translucent =NO;
在ios7中viewController使用了全屏布局的方式,也就是说导航栏和状态栏都是不占实际空间的,状态栏默认是全透明的,导航栏默认是毛玻璃的透明效果,也即坐标y= 0是屏幕最上方,将穿透属性设为NO,坐标Y=0为导航栏下边。问题解决了,但是请看下面两张图对比:
再看代码:
- (void)viewDidLoad {
[superviewDidLoad];
UITextView *field1 = [[UITextViewalloc] initWithFrame:CGRectMake(0,0, 150, 200)];
field1.backgroundColor = [UIColorredColor];
field1.font = [UIFontsystemFontOfSize:80];
[self.viewaddSubview:field1];
UITextView *field2 = [[UITextViewalloc] initWithFrame:CGRectMake(150,0, 150, 200)];
field2.backgroundColor = [UIColororangeColor];
field2.font = [UIFontsystemFontOfSize:80];
[self.viewaddSubview:field2];
self.view.backgroundColor = [UIColorwhiteColor];
}代码中我们可以看到两个textview的顶点Y都等于0,但是第一个光标却发生偏移第二个光标位置正常。再上个相似例子:
代码如下:
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
UITableView *table = [[UITableViewalloc] initWithFrame:CGRectMake(0,0, 150,300) style:UITableViewStylePlain];
table.delegate = self;
table.dataSource = self;
table.rowHeight = 80;
[self.viewaddSubview:table];
UITableView *table2 = [[UITableViewalloc] initWithFrame:CGRectMake(150,0, 150,300) style:UITableViewStylePlain];
table2.delegate = self;
table2.dataSource = self;
table2.rowHeight = 80;
[self.viewaddSubview:table2];
// Do any additional setup after loading the view.
}
图中2个tableview共用一套代理方法,就不贴出来了,我们发现左侧table初始位置在导航栏下方,右侧table初始位置在屏幕最上方。这是因为iOS7之后,视图控制器多了automaticallyAdjustsScrollViewInsets这个属性,官方文档是这么写的:
The default value of this property is YES, which allows the view controller to adjust its scroll view insets in response to the screen areas consumed by the status bar, navigation bar, and toolbar or tab bar. Set to NO if you want to manage scroll view inset adjustments yourself, such as when there is more than one scroll view in the view hierarchy. |
self.automaticallyAdjustsScrollViewInsets =NO;
从官方文档中看到,当 automaticallyAdjustsScrollViewInsets 这个属性为YES时,影响试图控制器调整scrollview的因素有状态栏,导航栏,标签栏,前一种解决方法只是消除了状态栏和导航栏的影响,第二种方法则取消了试图控制器对scrollview的调整功能,使scrollview按照我们的设定进行显示。此外还有一种方法,与第一种类似:
self.edgesForExtendedLayout =UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars =NO;