Position of rightView UITextField

前端 未结 3 1080
失恋的感觉
失恋的感觉 2021-01-04 18:21

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 li

相关标签:
3条回答
  • 2021-01-04 18:52

    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 ;
    }
    
    0 讨论(0)
  • 2021-01-04 19:05

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

    0 讨论(0)
  • 2021-01-04 19:13

    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
    
    0 讨论(0)
提交回复
热议问题