Position of rightView UITextField

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-19 05:32:30

问题


Is there a way to adjust the position of a rightView on UITextField? I tried setting the frame on the view (set as rightView) but it didn't change anything.

I'd like to avoid making two views, one as the rightView and one as the rightView's subview where I change the subview's position, if possible.


回答1:


The right overlay view is placed in the rectangle returned by the rightViewRectForBounds: method of the receiver.

So I suggest you subclass UITextField and override this method, something like this:

@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 ;
}



回答2:


@Puneet Sharma's answer was great but that would give the need to create a class that would subclass UITextField, what I did instead was create a UIView that would act as a padding.

My code works without the need to subclass

Here's my code, although it's written in 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

What happened here is, that the rightView which is a UIView that has a transparent colored background which then gave the illusion that there is a padding whereas there is not.




回答3:


Right Padding you can use as

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


来源:https://stackoverflow.com/questions/18371053/position-of-rightview-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!