【问题标题】:UIButton with changing text within a UITextField在 UITextField 中更改文本的 UIButton
【发布时间】:2017-10-15 08:30:22
【问题描述】:

我正在尝试添加一个“忘记密码”按钮作为我的文本字段的右视图。文本字段具有自定义样式,也应应用于按钮,因此按钮必须位于文本字段内。

到目前为止,我所拥有的是:

let forgotPasswordButton = UIButton()
forgotPasswordButton.setTitle("Forgot", for: .normal)
forgotPasswordButton.addTarget(self, action: #selector(forgotPassword), for: [.touchUpInside])

passwordTextField.rightView = forgotPasswordButton
passwordTextField.rightViewMode = .always

问题是,我的按钮是不可见的。经过一番谷歌搜索后,我意识到我应该将框架设置为按钮,而不是使用 .zero 进行初始化。但问题在于按钮的标题是本地化的,因此具有不同的宽度。

我该如何解决这个问题?

【问题讨论】:

    标签: ios swift uibutton uitextfield


    【解决方案1】:

    你应该从 NSString 方法 size 获得大小:

    // Create Label
    let forgotPasswordButton = UIButton()
    forgotPasswordButton.backgroundColor = .red
    
    // Title and font
    let title = "Forgot my wallet in the appartment"
    let font = forgotPasswordButton.titleLabel?.font
    
    // Set title
    forgotPasswordButton.setTitle(title, for: .normal)
    
    // Get size of title
    let fontAttributes = [NSFontAttributeName: font]
    let size = (title as NSString).size(attributes: fontAttributes)
    
    // Set frame using found size
    forgotPasswordButton.frame = CGRect(origin: .zero, size: size)
    

    然后你用大小做你的逻辑。

    【讨论】:

    • 是的,但我不想缩小标签,我想保持字体大小不变,从而在文本字段的右侧占用或多或少的空间。
    • 好的,抱歉。我不明白。我已经更新了我的答案。
    【解决方案2】:

    U 可以创建一个基于自定义类的 UITextfield ,并像这样覆盖这个选择器:

    ```

    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
            var rect = super.rightViewRect(forBounds: bounds);
            rect.size.width = rect.size.width*2;
            rect.size.height = rect.size.height*2;
            return rect;
        }
    

    ```
    您可以通过这种方式根据您的需要自定义矩形;

    【讨论】:

    • 这并不能解决根据按钮标题的文本获得确切宽度的问题。
    • 你可以通过你的按钮标题获取按钮的宽度,然后这样设置按钮的宽度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2011-10-24
    相关资源
    最近更新 更多