【问题标题】:How to limit text length to fit width of dynamically created UITextField如何限制文本长度以适应动态创建的 UITextField 的宽度
【发布时间】:2013-04-25 13:51:10
【问题描述】:

我动态创建了具有不同宽度和字体大小的UITextFields。我知道如何限制UITextField 中的文本长度,但我只能使用固定字符数来做到这一点。我需要的是动态限制字符数以适应某些UITextFields。我想每次输入新字符时我都应该使用CGSize 并获取特定字体大小的文本长度,而不是将其与 UITextField 宽度进行比较,如果超过UITextField 宽度则限制字符数。不幸的是,我不确定如何启动它。有谁知道任何可以帮助我的代码 sn-ps?

【问题讨论】:

    标签: ios objective-c xcode ios6 uitextfield


    【解决方案1】:

    你可以从这段代码开始:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSString *text = textField.text;
        text = [text stringByReplacingCharactersInRange:range withString:string];
        CGSize textSize = [text sizeWithFont:textField.font];
    
        return (textSize.width < textField.bounds.size.width) ? YES : NO;
    }
    

    在 ios 7 之后,它将 sizeWithFont 更改为 sizeWithAttributes。

    以下是修改后的代码:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSString *text = textField.text;
        text = [text stringByReplacingCharactersInRange:range withString:string];
        CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:textField.font}];
    
        return (textSize.width < textField.bounds.size.width) ? YES : NO;
    }
    

    【讨论】:

    • 我也发现这行得通,只需从文本字段中提取默认属性: CGSize textSize = [text sizeWithAttributes:[textfield defaultTextAttributes]];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2015-02-05
    相关资源
    最近更新 更多