Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position of rightView UITextField

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.

like image 904
Awesome-o Avatar asked Aug 22 '13 03:08

Awesome-o


2 Answers

@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.

This 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.

like image 176
Zonily Jame Avatar answered Oct 15 '22 10:10

Zonily Jame


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 ;
}
like image 41
Puneet Sharma Avatar answered Oct 15 '22 10:10

Puneet Sharma