Ios UIExtField中具有更改文本的UIButton

Ios UIExtField中具有更改文本的UIButton,ios,swift,uibutton,uitextfield,Ios,Swift,Uibutton,Uitextfield,我试图添加一个“忘记密码”按钮作为我文本字段的右视图。文本字段具有自定义样式,也应应用于按钮,因此按钮必须位于文本字段内部 到目前为止,我得到的是: let forgotPasswordButton = UIButton() forgotPasswordButton.setTitle("Forgot", for: .normal) forgotPasswordButton.addTarget(self, action: #selector(forgotPassword), for: [.touc

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

到目前为止,我得到的是:

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

passwordTextField.rightView = forgotPasswordButton
passwordTextField.rightViewMode = .always
问题是,我的按钮不可见。在谷歌搜索之后,我意识到我应该将框架设置为按钮,而不是使用
.zero
初始化。但问题是按钮的标题是本地化的,因此具有不同的宽度


如何解决此问题?

您应该从NSString方法大小中获取大小:

// 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)

然后对大小进行逻辑处理。

U可以创建一个自定义的基于类的UITextfield,并按如下方式重写此选择器:

```

```

你可以通过这种方式根据需要定制rect

这并不能解决基于按钮标题文本的精确宽度问题。您可以使用按钮标题获取按钮的宽度,然后以这种方式设置按钮的宽度。是的,但我不想缩小标签,我想保持字体大小不变,并相应地在文本字段的右侧占用更多或更少的空间。好的,对不起。我不明白。我已经更新了我的答案。
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;
    }