Iphone 如何知道文本是否超出了文本视图的边界?
我想知道文本何时超出UITextView的界限,并要求用户滚动。知道某个字体将占用多少行是无用的——我如何知道某个文本量将占用多少行Iphone 如何知道文本是否超出了文本视图的边界?,iphone,objective-c,ios,ipad,Iphone,Objective C,Ios,Ipad,我想知道文本何时超出UITextView的界限,并要求用户滚动。知道某个字体将占用多少行是无用的——我如何知道某个文本量将占用多少行 在上面的图片中,我会添加淡入淡出效果,这样我可以优雅地切断文本视图。但是,如果没有足够的文本可滚动,则显示淡入淡出看起来不正确。获取文本视图的属性文本,并使用以下方法计算大小: - (CGSize) size; 然后,您可以在了解文本视图的边界和此UIFont属性的情况下执行此工作: @property(nonatomic,readonly) CGFloat
在上面的图片中,我会添加淡入淡出效果,这样我可以优雅地切断文本视图。但是,如果没有足够的文本可滚动,则显示淡入淡出看起来不正确。获取文本视图的属性文本,并使用以下方法计算大小:
- (CGSize) size;
然后,您可以在了解文本视图的边界和此UIFont属性的情况下执行此工作:
@property(nonatomic,readonly) CGFloat lineHeight;
注意,属性字符串的大小只对长度有用,因为它认为文本在同一行上,而且不考虑行之间的空间。
< P>我编写了一个自定义AppDetrATE方法,可以在应用程序的几个位置上调用几种用法。方便地确定高度,以完全适合视图中的文本、自定义单元格高度、具有动态文本数据的表格行高度以及文本视图等示例逻辑:
//Logic Example:
if([appDelegate calculateTextHeight:@"Your_String_Passed_In_Here"] > textView.frame.size.height) {
//Text will exceed Height of TextView and require scroll.
}else {
//Text is within the TextView without need to scroll.
}
-(NSInteger)calculateTextHeight:(NSString *)text:(NSInteger)FontSize:(NSInteger)MaxWidth:(NSInteger)MinHeight:(NSInteger)optionalHeightPadding {
//Determine the Size based on the Inputs:
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FontSize] constrainedToSize:CGSizeMake(MaxWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
//Add Optional Padding:
int calH = size.height + optionalHeightPadding;
//Determine if larger than Min:
if (calH > MinHeight) {
return size.height + optionalHeightPadding;
}
//Return Min
return MinHeight;
}
方法:
//Logic Example:
if([appDelegate calculateTextHeight:@"Your_String_Passed_In_Here"] > textView.frame.size.height) {
//Text will exceed Height of TextView and require scroll.
}else {
//Text is within the TextView without need to scroll.
}
-(NSInteger)calculateTextHeight:(NSString *)text:(NSInteger)FontSize:(NSInteger)MaxWidth:(NSInteger)MinHeight:(NSInteger)optionalHeightPadding {
//Determine the Size based on the Inputs:
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FontSize] constrainedToSize:CGSizeMake(MaxWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
//Add Optional Padding:
int calH = size.height + optionalHeightPadding;
//Determine if larger than Min:
if (calH > MinHeight) {
return size.height + optionalHeightPadding;
}
//Return Min
return MinHeight;
}
提示:我以前使用UILineBreakModeWordWrap,但从iOS 6开始就不推荐使用它,请改用NSLineBreakByWordWrapping。设置文本后获取
contentSize
。这是一个CGSize,高度将是UITextView在不滚动的情况下显示文本所需的高度
myTextView.text = someText;
CGSize textSize = myTextView.contentSize;
float verticalSpaceNeededByText = textSize.height;
更新为Swift 3.x
func textExceedBoundsOf(_ textView: UITextView) -> Bool {
let textHeight = textView.contentSize.height
return textHeight > self.textView.bounds.height
}