Muli
Muli

Reputation: 214

Right margin of custom clear button in iOS

I create a custom clear button on my text field with a background image set. I position it on the right view but it always positions with a default margin. What I want is to have a right margin, for example, of 8.

extension UITextField {

    func clearButtonWithImage(_ image: UIImage) {
        let clearButton = UIButton()
        clearButton.setBackgroundImage(image, for: .normal)
        clearButton.alpha = 0.25
        clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(self.clear(sender:)), for: .touchUpInside)
        self.rightViewMode = .always
        self.clearButtonMode = .never
        self.rightView = clearButton
    }

    @objc func clear(sender: AnyObject) {
        self.text = ""
    }
}

I use a custom textfield class for changing the style of my textfield on selecting. My custom Textfield Class:

class customSearchTextField: customTextField {
    override var isSelected: Bool {
        didSet {
            setSelected(isSelected)
        }
    }

    private func setSelected(_ selected: Bool) {
        //UIView.animate(withDuration: 0.15, animations: {
        self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
        self.cornerRadius = selected ? 2.0 : 0.0
            if selected {
                self.clearButtonWithImage(UIImage())
            } else {
                self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
            }
        self.layer.shadowColor = UIColor .customDark.cgColor
        self.layer.shadowOpacity = selected ? 0.19 : 0.0
        //})
    }
}

Tried positioning the image frame but it always stays the same.

Upvotes: 1

Views: 1589

Answers (1)

trungduc
trungduc

Reputation: 12154

You should take a look at rightViewRect(forBounds:) method. Create a subclass of UITextField and custom position and size of clear button inside this method.

For example

class customSearchTextField: customTextField {
  override var isSelected: Bool {
    didSet {
      setSelected(isSelected)
    }
  }

  private func setSelected(_ selected: Bool) {
    //UIView.animate(withDuration: 0.15, animations: {
    self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
    self.cornerRadius = selected ? 2.0 : 0.0
    if selected {
      self.clearButtonWithImage(UIImage())
    } else {
      self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
    }
    self.layer.shadowColor = UIColor .customDark.cgColor
    self.layer.shadowOpacity = selected ? 0.19 : 0.0
    //})
  }

  override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
    var rect = super.rightViewRect(forBounds: bounds)
    rect.origin.x -= 30 // Assume your right margin is 30
    return rect
  }
}

Upvotes: 1

Related Questions