【问题标题】:How to set limited width of text in uitextfield如何在uitextfield中设置有限的文本宽度
【发布时间】:2012-06-02 07:30:12
【问题描述】:

我需要在UITextField 中设置有限的文本宽度,因为我将按钮放在了UITextField 之上

看图:

如何做到这一点?

【问题讨论】:

  • 这是 UITableViewCell 吗?如果是这样,它有一个简单的方法来使用附件视图。

标签: ios xcode uitextfield width limit


【解决方案1】:

除此之外,您可能希望同时覆盖editingRectForBoundstextRectForBounds,以便在编辑和不编辑时正确显示文本(请参阅this post)。在 Swift 中,这可能是:

class MyUITextField: UITextField {

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, 18, 0)
    }

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, 18, 0)
    }
}

【讨论】:

    【解决方案2】:

    您可以将 UITextView 的事件editingChanged 链接到以下方法:

    - (IBAction)textFieldChanged:(id)sender{
        if([sender.text length]>6){ 
            sender.text = [sender.text substringToIndex: 6];
        }
    }
    

    【讨论】:

    • +1--我以前做过类似的事情。但是,如果您不使用等宽字体,则必须小心,因为这样并不总是有效。
    • 使用此解决方案,您将文本限制为 6 个字符,我认为这是不希望的。他只想更改插图,以免按钮覆盖字符。查看我的解决方案..
    • 我明白他只是想限制文本的大小,比如你最多可以输入 10 个字符。
    • 另一种选择是将具有所需宽度且没有边框的真实 uitextview 放在背景上禁用的 uitextview 前面。这样,它会在看起来像一个带有按钮的 UITextView 的同时获得所需的效果。
    • 谢谢大家..我会记住你的方法
    【解决方案3】:

    您可能需要继承 UITextField 并覆盖 editingRectForBounds: 方法。尝试这样的事情。当然可以相应地调整值。

    - (CGRect)editingRectForBounds:(CGRect)bounds {
          return CGRectInset( bounds , 10 , 10 );
    }
    

    如果它可以解决您的问题,请接受此答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多