尝试类似:
NSArray *subStrings = [myTextView.text componentsSeparatedByString: @"\n"];
textField1.text=subStrings[0];
textField2.text=subStrings[1];
如果你的 textView 没有任何 \n 字符,那么你需要做更多的工作来获取基于行的 textview 文本。
试试这个:
- (void)viewDidLoad {
[super viewDidLoad];
//set the textView in storyboard or you can do it here:
textView.text=@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.";
//Initialise your array
yourArray=[[NSMutableArray alloc]init];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, index, numberOfGlyphs =
[layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
NSString *lineText= [textView.text substringWithRange:lineRange];
[yourArray addObject:lineText];
}
textField1.text=yourArray[0];
textField2.text=yourArray[1];
}
此代码假定您有一个对textView 的引用,该textView 配置了一个布局管理器、文本存储和文本容器。 textView 返回对布局管理器的引用,然后返回其关联文本存储中所有字符的字形数,执行字形 em> 必要时生成。然后 for 循环开始布置文本并计算生成的行片段。 NSLayoutManager 方法 lineFragmentRectForGlyphAtIndex:effectiveRange: 强制在传递给它的索引处包含 glyph 的行布局。
该方法返回由行片段(此处忽略)占据的矩形,并通过引用返回布局后行中字形的范围。方法计算出一行后,NSMaxRangefunction返回比范围内最大值大一的索引,即下一行第一个字形的索引。 numberOfLines 变量递增,for 循环重复,直到 index 大于文本中的字形数量,此时 numberOfLines 包含布局过程产生的行数,由自动换行定义。
了解更多info.
然后你就可以了
textField1.text=yourArray[0];
textField2.text=yourArray[1];
对于第一次迭代,字符串 lineText 将包含 textview 的第一行,而对于第二次迭代,它将包含 textView 的第二行。