Position of rightView UITextField

前端 未结 3 1081
失恋的感觉
失恋的感觉 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 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.

提交回复
热议问题