我有计算UITextField中显示的NSString的准确大小的问题。计算NSString大小以调整UITextField帧
我的目标是以编程方式根据字符串大小更新文本框的大小(不使用sizeToFit)。我正在使用sizeWithFont函数。
-(void)resizeTextFieldAccordingToText:(NSString*)textFieldString {
CGPoint originalCenter = self.textField.center;
UIFont* currentFont = [textField font];
CGSize newSize = [textFieldString sizeWithFont:currentFont];
//Same incorrect results with the extended version of sizeWithFont, e.g.
//[textFieldString sizeWithFont:currentFont constrainedToSize:CGSizeMake(300.0, 100.0) lineBreakMode:NSLineBreakByClipping];
[self.textField setFrame:(CGRectMake(self.textField.frame.origin.x, self.textField.frame.origin.y, newSize.width, newSize.height))];
[self.textField setCenter:originalCenter];
}
问题:尽管该返回正确的大小的结果在第一其变为通过将字符越来越unprecise因此终于开始夹住的字符串(如在右屏幕截图所示)。
如何获得文本域字符串正确地调整它的大小尺寸准确?
可能是这个职位可能是有用于你的目的:http://stackoverflow.com/questions/1435544/measuring-the-pixel-width-of-a-string – RFG
我知道这一点,但即使使用这个扩展版本的sizeWithFont(例如CGSize newSize = [ textFieldString sizeWithFont:currentFont constrainedToSize:CGSizeMake(300.0,100.0)lineBreakMode:NSLineBreakByClipping];)会返回相同的稍微不正确的大小。 – Bernd
是的,因为它没有考虑填充 –