谢谢大家的回答!这给了我一些想法,并且能够解决问题。我希望这可以帮助其他有类似问题的人。首先,再次澄清问题陈述,结果如下形式:
NSString * result = [NSString stringWithFormat:@"%@ = %@", answerString, answerNumber];
通过计算 UITextView 内容视图中的行数(How do I size a UITextView to its content?),我能够通过以下方法解决问题:
首先,比较有答案和没有答案的 UITextView 中的行数。如果行数不同,那么这意味着 UITextView 已经决定将结果换行,在这种情况下,我应该重新格式化结果以在数字前手动添加换行符,以确保负号(数字的一部分)是新行的第一个字符:
- (int) numberOfLines: (NSString *) result {
UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 255, 0)];
myTextView.text = result;
CGRect frame = myTextView.frame;
frame.size.height = myTextView.contentSize.height;
myTextView.frame = frame;
int numLines = myTextView.contentSize.height / myTextView.font.lineHeight;
return numLines;
}
- (NSString *) formatResult: (NSString *) answerString answerNumber: (NSString *) answerNumber {
NSString * resultWithoutAnswer = [NSString stringWithFormat:@"%@ = ", answerString];
NSString * resultWithAnswer = [NSString stringWithFormat:@"%@ = %@", answerString, answerNumber];
NSString * result = resultWithAnswer;
if ([self numberOfLines:resultWithoutAnswer] != [self numberOfLines:resultWithAnswer]) {
// If these are different, then UITextView has added a line break before the answer. To prevent UITextView from potentially splitting the number across the negative sign, manually add a line break to ensure that the negative sign shows on the same line as the number.
result = [NSString stringWithFormat:@"%@ = \n%@", answerString, answerNumber];
}
return result;
}