【问题标题】:Position of rightView UITextFieldrightView UITextField 的位置
【发布时间】:2013-08-22 03:07:51
【问题描述】:

有没有办法在 UITextField 上调整 rightView 的位置?我尝试在视图上设置框架(设置为 rightView),但没有任何改变。

我想避免创建两个视图,一个作为 rightView,一个作为 rightView 的子视图,如果可能的话,我会在其中更改子视图的位置。

【问题讨论】:

  • 你试过[textField.rightView setFrame:someFrame];?或者setBounds:.
  • 您需要获得 2 次观看。

标签: ios objective-c uikit uitextfield


【解决方案1】:

右覆盖视图放置在接收者的rightViewRectForBounds:方法返回的矩形中。

所以我建议你继承 UITextField 并覆盖这个方法,像这样:

@interface CustomTextField: UITextField

@end

@implementation CustomTextField

// override rightViewRectForBounds method:
- (CGRect)rightViewRectForBounds:(CGRect)bounds{
    CGRect rightBounds = CGRectMake(bounds.origin.x + 10, 0, 30, 44);
    return rightBounds ;
}

【讨论】:

  • 酷。但是我发现对于正确的视图标注,我最好使用 bounds.size.width - 30 即 CGRect rightBounds = CGRectMake(bounds.size.width - 30, 0, 30, 50);通过这种方式,它可以获取文本字段的宽度并减去该数字以获得正确视图的填充
【解决方案2】:

@Puneet Sharma 的回答很棒,但这需要创建一个继承 UITextField 的类,而我所做的是创建一个用作填充的 UIView。

此代码无需子类即可工作

这是我的代码,虽然它是用 Swift 3

编写的
// this is the view I want to see on the rightView
let checkImageView = UIImageView(image: UIImage(named: "check24.png"))
checkImageView.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
checkImageView.curveEdges(12)
checkImageView.contentMode = .scaleAspectFit

// declare how much padding I want to have
let padding: CGFloat = 6

// create the view that would act as the padding
let rightView = UIView(frame: CGRect(
    x: 0, y: 0, // keep this as 0, 0
    width: checkImageView.frame.width + padding, // add the padding
    height: checkImageView.frame.height)) 
rightView.addSubview(checkImageView)

// set the rightView UIView as the textField's rightView
self.textField.rightViewMode = .whileEditing
self.textField.rightView = rightView

这里发生的事情是,rightView 是一个 UIView,它有一个透明的彩色背景,然后给人一种有填充而没有填充的错觉。

【讨论】:

    【解决方案3】:

    你可以使用右边的填充

    let imageview = UIImageView(image: UIImage(named: "image name"))
    imageview.contentMode = .center
    
    let rightPadding: CGFloat = 14 //--- change right padding 
    imageview.frame = CGRect(x: 0, y: 0, width: imageview.frame.size.width + rightPadding , height:imageview.frame.size.height)
    
    textField.rightViewMode = .always
    textFieldd.rightView = imageview
    

    【讨论】: