UITextView文本不从顶部开始

我有一个UITextView 。 我希望它的文本从顶端开始,但是我不是从顶端开始的。 请看看我的代码:

 UITextView *myTextView = [[UITextView alloc] init]; myTextView.frame = rect; myTextView.editable = NO; myTextView.font = [UIFont fontWithName:@"Helvetica" size:MAIN_FONT_SIZE]; myTextView.backgroundColor = [UIColor clearColor]; myTextView.text = sourceNode.label; myTextView.dataDetectorTypes = UIDataDetectorTypeAll; [cell.contentView addSubview:myTextView]; [myTextView sizeToFit]; [self alignTextToTopTextView:myTextView]; 

alignTextToTopTextView

 -(void)alignTextToTopTextView :(UITextView*)textView{ CGRect frame = textView.frame; frame.size.height = textView.contentSize.height; textView.frame = frame; } 

请看下面的截图

UITextView在右侧。

在这里输入图像说明

在你的UITextView中像这样设置Content Inset

 youtextView.contentInset = UIEdgeInsetsMake(-7.0,0.0,0,0.0); 

以您想要的方式调整Top值。 这应该解决你的问题。

编辑:

如果您在使用iOS7或更高版本时遇到问题,请尝试使用…

[yourTextView setContentOffset:CGPointMake(x,y)animated:BOOL];

在viewDidLoad方法中添加

 self.automaticallyAdjustsScrollViewInsets = false 

我是这样做的 当滚动禁用,从顶部加载的文本。 加载之后启用滚动。

 - (void)viewDidLoad{ myTextView.scrollEnabled = NO; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; myTextView.scrollEnabled = YES; } 

现有的解决scheme都没有帮助,但这有助于

Objective-C的:

 - (void)viewDidLayoutSubviews { [self.yourTextView setContentOffset:CGPointZero animated:NO]; } 

Swift 3

 override func viewDidLayoutSubviews() { textView.setContentOffset(CGPoint(x: 0, y: 0), animated: false) } 

这是我用的

 textView.textContainerInset = UIEdgeInsetsMake( 0, -textView.textContainer.lineFragmentPadding, 0, -textView.textContainer.lineFragmentPadding ) ; 
 - (void) viewDidLoad { [textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL]; [super viewDidLoad]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { UITextView *tv = object; //Center vertical alignment //CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0; //topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect ); //tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect}; //Bottom vertical alignment CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height); topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect); tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect}; } 

这是答案

在Swift中

 termsTextView.contentOffset = CGPointMake(0, -220) 

在Objective-C中

 [termsTextView setContentOffset: CGPointMake(0,-220) animated:NO]; 

在iOS 7和8中设置UITextViewautoresizingMask属性之后,会发生这种情况。

我发现一个可选的解决方法:

 - (void)viewWillAppear:(BOOL)animated { [super viewDidAppear:animated]; [yourTextView scrollRectToVisible:CGRectMake(0, 0, yourTextView.contentSize.width, 10) animated:NO]; } 

self.yourTextView.scrollEnabled = NO;

self.yourTextView.textContainerInset = UIEdgeInsetsMake(0,0,0,0);