• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何根据 TextField 的可见大小限制 UITextField 的输入文本量?

[复制链接]
菜鸟教程小白 发表于 2022-12-12 13:17:50 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个表单应用程序,其中包含许多不同大小的 UITextField。我想将输入文本的数量限制为在截断字符串之前文本字段可以容纳多少文本。关于堆栈溢出的所有其他答案似乎都知道事先限制字符的数量(例如,我想限制为 40 个字符),但我需要知道如何根据文本字段的大小(因文本字段而异)来限制它到文本字段)。

有没有办法做到这一点?

谢谢



Best Answer-推荐答案


由于字符串的长度取决于字符,因此您无法在知道它们之前确定最大字符数,因此我建议您在进行过程中测试每个字符输入是否适合文本字段,例如:

- (BOOL)textFieldUITextField *)textField shouldChangeCharactersInRangeNSRange)range replacementStringNSString *)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;
    }
}

关于ios - 如何根据 TextField 的可见大小限制 UITextField 的输入文本量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449895/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap