UITextField rightView移动到UITextFiled之外

时间:2014-12-29 00:48:41

标签: ios uitextfield

我正在尝试使用rightView类的UITextField属性为文本字段提供后缀。这一切似乎都正常工作,直到我停止编辑文本字段,此时标签移动到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
    }
}

首次加载视图时,视图如下所示:

enter image description here

但是,当编辑了文本字段然后键盘被解除时,它看起来如下所示:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

原来问题是再次设置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(),但这样做是有效的,所以我只是按原样离开。