gpt4 book ai didi

ios - UITextField rightView 移出 TextField

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:44 29 4
gpt4 key购买 nike

我正在尝试使用 UITextField 类的 rightView 属性为文本字段提供后缀。一切似乎都正常工作,直到我停止编辑文本字段,此时标签被移到 UITextField 之外。使用的代码是:

class TextFieldWithSuffix: UITextField {
var suffix: String? {
didSet {
let value = self.suffix ?? ""
let label = UILabel(frame: CGRectZero)
label.font = self.font
label.text = value

self.rightView = label
self.rightViewMode = .Always
}
}

override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
var rightViewRect = super.rightViewRectForBounds(bounds)
if let suffix = self.suffix {
let suffixSize = NSString(string: suffix).sizeWithAttributes([NSFontAttributeName: self.font])
rightViewRect.size = suffixSize
}
return rightViewRect
}
}

首次加载 View 时, View 如下所示:

enter image description here

然而,当文本字段被编辑然后键盘消失时,它看起来像下面这样:

enter image description here

这已经在 iOS 7 和 8 上进行了测试,两者似乎都在做同样的事情。

最佳答案

原来问题出在再次设置 rightView 属性,这是在编辑完成时发生的。我发现以下版本解决了这个问题:

class TextFieldWithSuffix: UITextField {
var suffix: String? {
didSet {
let value = self.suffix ?? ""

let suffixLabel = UILabel(frame: CGRectZero)
suffixLabel.font = self.font
suffixLabel.updateFontStyle()
suffixLabel.text = value

self.rightView = nil
self.rightView = suffixLabel
self.rightViewMode = .Always

self.setNeedsLayout()
self.layoutIfNeeded()
}
}

override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
var rightViewRect = super.rightViewRectForBounds(bounds)
if let suffix = self.suffix {
let suffixSize = NSString(string: suffix).sizeWithAttributes([NSFontAttributeName: self.font])
rightViewRect.size = suffixSize
}
return rightViewRect
}
}

希望这会对某人有所帮助。如果你经常这样做,你应该只更新标签的值并调用 setNeedsLayout()layoutIfNeeded(),但这是可行的,所以我只是保持原样。

关于ios - UITextField rightView 移出 TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27682139/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com