我有一个表单应用程序,其中包含许多不同大小的UITextField。我想将输入文本的数量限制为截断字符串之前文本字段可以容纳的文本数量。堆栈溢出的所有其他答案似乎都知道限制手头字符的数量(例如,我想限制为40个字符),但是我需要知道如何根据文本字段的大小来限制它(这取决于文本字段)到文本字段)。
有没有办法做到这一点?
谢谢
由于字符串的长度取决于字符,因此您无法在知道字符之前确定最大字符数,因此我建议您在测试过程中测试每个字符输入是否适合文本字段,例如:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Combine the new text with the old
NSString *combinedText = [textField.text stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%@", string]];
// See if the width of the combined text + the text field's
// left layout margin + the text field's right layout margin
// is greater than or equal to the width of the textField
// (I've multiplied the right margin by 2 to prevent the cursor
// from shifting the field one extra character when the text field
// if full)
CGFloat textWidth = [combinedText sizeWithAttributes:@{NSFontAttributeName: textField.font}].width + textField.layoutMargins.left + textField.layoutMargins.right * 2;
CGFloat textFieldWidth = textField.frame.size.width;
// If the text + margins is as wide or wider than the text field
// don't add the new character, i.e. return NO. Else add the
// character by returning YES.
if (textWidth >= textFieldWidth) {
return NO;
} else {
return YES;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句