如何更改UITextField leftview框架

时间:2014-03-11 12:08:56

标签: ios objective-c uitextfield

如何更改leftView中的UITextField的位置?

我试过这个,但leftView位置没有改变

UIView *view = [[UIView alloc]init];
[view setFrame:CGRectMake(10, 10, 15, 15)];
[view setBackgroundColor:[UIColor blackColor]];
[self.urlBar setLeftView:view];
[self.urlBar setLeftViewMode:UITextFieldViewModeAlways];

5 个答案:

答案 0 :(得分:8)

要更改leftView的位置,您需要创建自己的UITextField子类,并覆盖leftViewRectForBounds:方法以返回不同的框架。

答案 1 :(得分:2)

以下代码将从左侧为您提供20的填充(位移)。

@IBDesignable
class LeftImageTextField: UITextField {

let displacement: CGFloat = 20

required override public init(frame: CGRect) {
    super.init(frame: frame)
    sharedSetup()
}

required public init?(coder: NSCoder) {
    super.init(coder: coder)
    sharedSetup()
}

func sharedSetup() {
    self.leftViewMode = .always
    self.leftView = UIImageView(image: UIImage(named: "myImage"))
}

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    var textRect = super.leftViewRect(forBounds: bounds)
    textRect.origin.x += displacement
    return textRect
}

// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.textRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.editingRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
    return bounds
}

/**
 Changes to this parameter draw the border of `self` in the given width.
 */
@IBInspectable
var leftImage: UIImage? {
    didSet {
        self.leftView = UIImageView(image: leftImage)
    }
}
}

答案 2 :(得分:2)

Swift 5 上的 iOS 13 解决方案:

let padding: CGFloat = 8
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: padding * 2 + 23, height: 23))
let imageView = UIImageView(frame: CGRect(x: padding, y: 0, width: 23, height: 23))
imageView.image = image
outerView.addSubview(imageView)
leftView = outerView // Or rightView = outerView
leftViewMode = .always // Or rightViewMode = .always

答案 3 :(得分:1)

对于iOS 13,您可以添加这些行(它们对13之前的版本没有影响)

view.WidthAnchor.ConstraintEqualTo(15).Active = true;
view.HeightAnchor.ConstraintEqualTo(15).Active = true;

这是Xamarin代码,但我想您应该能够将其转换为Swift / ObjectiveC。

答案 4 :(得分:0)

无需制作子类。

UIView *leftView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, self.yourTextField.frame.size.height)];
leftView2.backgroundColor = [UIColor clearColor];
self.yourTextField.leftView = leftView2;
self.yourTextField.leftViewMode = UITextFieldViewModeAlways;