Change lazy button opacity from outside of the class - ios

I need to change alpha value of the button in another class. But the problem is button created as "lazy var" so I can not change that value.
lazy var middleButton: UIButton = {
let button = UIButton(type: .custom)
button.frame.size = CGSize(width: 56, height: 56)
button.layer.cornerRadius = button.frame.width / 2
button.layer.masksToBounds = true
button.backgroundColor = .white
button.setImage(UIImage(named: "iconBasket"), for: .normal)
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
button.addTarget(self, action: #selector(btnBasketClicked))
addSubview(button)
return button
}()
I want this button's alpha as 0.2 when view is scrolling. Here is the code
extension ProductListView: UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0{
// alpha = 0.2
MyTabBar.shared.scrollDown()
}
else{
// alpha = 1.0
MyTabBar.shared.scrollUp()
}
}
}
func scrollDown(){
middleButton.alpha = 0.2
}
I've tried lots of way but doesn't work. Calling "addSubView()" function in "layoutSubviews()" solve my problem but this causes another problem which my function "basketButtonClicked()" are not called. I used Delegate pattern and here it is.
protocol BasketButtonDelegate: class {
func basketButtonClicked()
}
#objc private func btnBasketClicked(_ sender: UIButton!){
delegate?.basketButtonClicked()
}
override func layoutSubviews() {
super.layoutSubviews()
addSubview(middleButton)
}
When I call "addSubView" function in "layoutSubviews()", "basketbuttonClicked" never called.
extension TabCoordinator : BasketButtonDelegate
{
func basketButtonClicked(){
log.debug("basketButtonClicked")
let coor = CartCoordinator(navigationController, hidesBar: true)
childCoordinators.append(coor)
coor.start()
}
}
(I assigned delegate so the problem is not about it.)
A bit complicated but I hope we can figure it out.

You need to add protocol to your MyTabBar class . It should be like this
class MyTabBar {
static var shared = MyTabBar()
weak var delegate : abc?
func scrollDown(){
delegate?.xyz()
}
}
protocol abc : AnyObject {
func xyz()
}
And in your class
class btnView : UIView , abc{
lazy var middleButton: UIButton = {
let button = UIButton(type: .custom)
button.frame.size = CGSize(width: 56, height: 56)
button.layer.cornerRadius = button.frame.width / 2
button.layer.masksToBounds = true
button.backgroundColor = .red
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
button.addTarget(self, action: #selector(btnBasketClicked), for: .touchUpInside)
return button
}()
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
#objc func btnBasketClicked(){
print("Im here")
}
func addMiddleButton(){
self.addSubview(middleButton)
}
func alphaaa(){
self.middleButton.alpha = 0.2
}
func xyz() {
self.alphaaa()
}
}
Last , in your ProductListView create and instance of your view , or if you add with autolayout just call 2. function in your viewDidLoad
var viewwww = btnView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
viewwww.addMiddleButton() // call to add btn to custom view
and extension
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0{
// alpha = 0.2
MyTabBar.shared.delegate = viewwww
MyTabBar.shared.scrollDown()
}
else{
// alpha = 1.0
MyTabBar.shared.scrollUp()
}
}

Related

Button and Image Alignment issues in UIButton

So I have a UIBarbuttonItem that I am currently designing based off of a layout that I have done.
import Foundation
import UIKit
class LocationManager: UIBarButtonItem {
var viewController: MainViewController?
lazy var customButton : UIButton = {
let customButton = UIButton(type: .system)
customButton.setImage(UIImage(named: "downArrow"), for: .normal)
customButton.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, -10)
guard let customFont = UIFont(name: "NoirPro-SemiBold", size: 20) else {
fatalError("""
Failed to load the "CustomFont-Light" font.
Make sure the font file is included in the project and the font name is spelled correctly.
"""
)
}
customButton.semanticContentAttribute = UIApplication.shared
.userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft
customButton.titleLabel?.font = customFont
customButton.setTitleColor(UIColor.black, for: .normal)
return customButton
}()
override init() {
super.init()
setupViews()
}
#objc func setupViews(){
customView = customButton
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I correctly do the job of using both an image and title and setting the image insets for the button and on load the appearance is great. However, when I leave the screen and come back it seems as though everything is thrown out of wack the image gets moved back and sometimes there will be two images and one will have a distorted size.
Is there anything wrong with my custom button implementation that I am missing.
I have included images for before and after
I suggest you to make your custom button class, then make title and image by adding subviews. In this case UIImageView and UILabel. Because UIButton inherits from UIView you can easy do this. I've never had problems using this way.
Here is the code I've written for you:
import UIKit
class ViewController: UIViewController {
lazy var customButton: CustomButton = {
let button = CustomButton(frame: CGRect(x: 50,
y: 200,
width: view.frame.width - 100,
height: 50))
// This mask for rotation
button.autoresizingMask = [.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleBottomMargin]
button.attrTitleLabel.text = "San Francisco, CA"
button.addTarget(self, action: #selector(chooseCity), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blue
view.addSubview(customButton)
}
#objc func chooseCity() {
print("Choose city button has pressed")
}
}
class CustomButton: UIButton {
private let arrowImageSize: CGSize = CGSize(width: 20, height: 20)
private let sideOffset: CGFloat = 10
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(attrTitleLabel)
addSubview(arrowImageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var attrTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "NoirPro-SemiBold", size: 20)
label.textColor = .black
return label
}()
lazy var arrowImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "arrow_down")
iv.contentMode = .scaleAspectFit
return iv
}()
override func layoutSubviews() {
super.layoutSubviews()
arrowImageView.frame = CGRect(x: self.frame.width - arrowImageSize.width - sideOffset,
y: self.frame.height/2 - arrowImageSize.height/2,
width: arrowImageSize.width,
height: arrowImageSize.height)
attrTitleLabel.frame = CGRect(x: sideOffset, y: 0, width: self.frame.width - sideOffset*2 - arrowImageSize.width, height: self.frame.height)
}
}
How it looks:

IBDesignable properties not updating during runtime

I have created a custom segmented control using this video (https://www.youtube.com/watch?v=xGdRCUrSu94&t=2502s) . I want to be able to change the string values displayed inside the custom segmented control (commaSeperatedButtonTitles) during runtime from 1,2,3,4 to 5,6,7,8 but for some reason the view is not updating the values. The values seem to be able to be changed in viewDidLoad but not inside action events which is what I need.
import UIKit
#IBDesignable
class CustomSegmentedControl: UIControl {
var buttons = [UIButton]()
var selector: UIView!
var selectedSegmentIndex = 0
#IBInspectable
var borderWidth: CGFloat = 0 {
didSet{
layer.borderWidth = borderWidth
}
}
#IBInspectable
var borderColor: UIColor = UIColor.gray {
didSet{
layer.borderColor = borderColor.cgColor
}
}
#IBInspectable
var commaSeperatedButtonTitles: String = "" {
didSet{
}
}
#IBInspectable
var textColor: UIColor = .lightGray {
didSet{
}
}
#IBInspectable
var selectorColor: UIColor = .blue {
didSet{
}
}
#IBInspectable
var selectorTextColor: UIColor = .white {
didSet{
}
}
func updateView(){
buttons.removeAll()
subviews.forEach { (view) in
view.removeFromSuperview()
}
var buttonTitles = commaSeperatedButtonTitles.components(separatedBy: ",")
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.addTarget(self, action: #selector(buttonTapped(button:)), for: .touchUpInside)
buttons.append(button)
}
buttons[0].setTitleColor(selectorTextColor, for: .normal)
let selectorWidth = (frame.width / CGFloat(buttonTitles.count))
selector = UIView(frame: CGRect(x: 0, y: 0, width: selectorWidth, height: frame.height))
selector.layer.cornerRadius = (frame.height / 2)
selector.backgroundColor = selectorColor
addSubview(selector)
let sv = UIStackView(arrangedSubviews: buttons)
sv.axis = .horizontal
sv.alignment = .fill
sv.distribution = .fillEqually
addSubview(sv)
sv.translatesAutoresizingMaskIntoConstraints = false
sv.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
sv.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
sv.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
sv.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
// Drawing code
layer.cornerRadius = (frame.height / 2)
//updateView()
}
override func layoutSubviews() {
updateView()
}
func buttonTapped(button: UIButton){
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == button{
selectedSegmentIndex = buttonIndex
let selectorStartPosition = (frame.width / CGFloat(buttons.count) * CGFloat(buttonIndex))
UIView.animate(withDuration: 0.3, animations: {
self.selector.frame.origin.x = selectorStartPosition
})
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
sendActions(for: .valueChanged)
}
}
Code in View Controller inside action event:
customSegment.commaSeperatedButtonTitles = "5,6,7,8"
It appears to me that updateView() method is not being called after you set the commaSeperatedButtonTitles property. Try calling it after the property is set:
#IBInspectable
var commaSeperatedButtonTitles: String = "" {
didSet {
self.updateView()
}
}
Another point worth mentioning: it's probably unnecessary to call updateView() every time on layoutSubviews() as it recreates all the buttons for your custom segmented control.

Event not triggering in UISlider programatically created in Swift 3

I have the following UICollectionViewCell subclass that I have a UISlider created without using storyboards:
class ProductDetailPersonalLoanViewCell: UICollectionViewCell {
let valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
mySlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
func setupViews(){
addSubview(valueSlider)
// ....... layout constraints
}
func sliderValueDidChange(_ sender:UISlider!){
print("Slider value changed")
let roundedStepValue = round(sender.value / step) * step
sender.value = roundedStepValue
print("Slider step value \(Int(roundedStepValue))")
}
}
The problem is that for some reason the event is not being triggered when I move the thumb, so I'm not able to use the UISlider value. Does someone know how to fix that?
You have to add target to your valueSlider outside of the computed value block:
let valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
valueSlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
}
or, which I think would be a better solution, change the computed value to a lazy property:
lazy var valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
mySlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}

Add a subview(ShareView) but nothing happens when touching a button on it

Add a subview(ShareView) but nothing happens when touching a button(coverBtn) on it if I shareVC.addsubView(self) in func showShareView ()
But If superView.addSubview(coverBtn) and superView.addSubview(sharePanel) separately, everything will be fine.
import UIKit
class ShareView: UIView {
weak var shareVC: UINavigationController?
// UI
private lazy var coverView: UIView! = {
let coverView = UIView(frame: UIScreen.mainScreen().bounds)
return coverView
}()
// transluscent cover
private lazy var coverBtn: UIButton! = {
let bounds = UIScreen.mainScreen().bounds
let frame = CGRectMake(0, 0, bounds.width, bounds.height)
let coverBtn = UIButton(frame: frame)
print ("UIScreen.mainScreen().bounds = \(UIScreen.mainScreen().bounds)")
coverBtn.alpha = 0.2
coverBtn.backgroundColor = UIColor.blackColor()
coverBtn.addTarget(self, action: #selector(ShareView.pressCoverBtn), forControlEvents: .TouchUpInside)
return coverBtn
}()
let panelHeight: CGFloat = 215
// share panel
private lazy var sharePanel: UIView! = {
// panel size
let bounds = UIScreen.mainScreen().bounds
let h = 215
let frame = CGRectMake(0, bounds.height, bounds.width, self.panelHeight)
let sharePanel: UIView = UIView(frame: frame)
sharePanel.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1.0)
// label
let labelHeight: CGFloat = 30
let labelWidth: CGFloat = 100
let labelY: CGFloat = 20
let labelFrame = CGRectMake(sharePanel.frame.width/2-labelWidth/2, labelY, labelWidth, labelHeight)
let label = UILabel(frame: labelFrame)
label.text = "分享到"
label.textAlignment = .Center
label.backgroundColor = UIColor.whiteColor()
sharePanel.addSubview(label)
// share buttons
let marginW: CGFloat = 80
let btnInv: CGFloat = 20
let btnCnt: CGFloat = 3
let btnsY = label.frame.maxY + 15
let btnA = (sharePanel.frame.width - 2*marginW - (btnCnt-1)*btnInv)/btnCnt
let wcFrame = CGRectMake(marginW, btnsY, btnA, btnA)
let pyqFrame = CGRectMake(wcFrame.maxX+btnInv, btnsY, btnA, btnA)
let wbFrame = CGRectMake(pyqFrame.maxX+btnInv, btnsY, btnA, btnA)
let wcBtn = UIButton(frame: wcFrame)
let pyqBtn = UIButton(frame: pyqFrame)
let wbBtn = UIButton(frame: wbFrame)
wcBtn.setImage(UIImage(named: "share_wx"), forState: .Normal)
pyqBtn.setImage(UIImage(named: "share_pyq"), forState: .Normal)
wbBtn.setImage(UIImage(named: "share_wb"), forState: .Normal)
sharePanel.addSubview(wcBtn)
sharePanel.addSubview(pyqBtn)
sharePanel.addSubview(wbBtn)
// cancel button
let ccW = sharePanel.frame.width/2
let ccH: CGFloat = 50
let ccFrame = CGRectMake(sharePanel.frame.width/2-ccW/2, wcBtn.frame.maxY+10, ccW, ccH)
let cancelBtn: UIButton = UIButton(frame: ccFrame)
cancelBtn.setBackgroundImage(UIImage(named: "kkk"), forState: .Normal)
cancelBtn.setTitle("取消", forState: .Normal)
cancelBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
cancelBtn.addTarget(self, action: #selector(ShareView.pressCoverBtn), forControlEvents: UIControlEvents.TouchUpInside)
sharePanel.addSubview(cancelBtn)
return sharePanel
}()
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
// override init(){
// super.init()
// }
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView (superView: UIView) {
superView.addSubview(coverBtn)
superView.addSubview(sharePanel)
}
#objc func pressCoverBtn() {
print("press cover btn\n")
hideShareView()
}
func showShareView () {
self.addCustomView((shareVC?.view)!)
UIView.animateWithDuration(0.4, animations: {
() -> Void in
self.sharePanel.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height - self.panelHeight, self.sharePanel.frame.width, self.panelHeight)
})
}
func hideShareView() {
coverBtn.removeFromSuperview()
UIView.animateWithDuration(0.4, animations: {
() -> Void in
self.sharePanel.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height, self.sharePanel.frame.width, self.panelHeight)
}) { (finish)-> Void in
self.removeFromSuperview()
}
}
}
you can check the 'Debug View Hierarchy' to focus on layers so that you can see if there is a view over the button blocking it
'Debug view Hierarchy' will give you 3d view of every layer
it is situated in bottom bar
Also, you are adding both the views to the superview, try to add 'coverBtn' button to the 'sharePanel' view and then add the view to the super view, this will create button layer above the 'sharePanel' view

Custom Clear Button

I want to create custom clear button on UITextField, that is to use rightView and put image there, the problem is attaching the original clear button event to that custom rightView.
In Objective-C i can do that this way:
SEL clearButtonSelector = NSSelectorFromString(#"clearButton");
// Reference clearButton getter
IMP clearButtonImplementation = [self methodForSelector:clearButtonSelector];
// Create function pointer that returns UIButton from implementation of method that contains clearButtonSelector
UIButton * (* clearButtonFunctionPointer)(id, SEL) = (void *)clearButtonImplementation;
// Set clearTextFieldButton reference to “clearButton” from clearButtonSelector
UIButton *_clearTextFieldButton = clearButtonFunctionPointer(self, clearButtonSelector);
[_clearTextFieldButton setImage:[UIImage imageNamed:#"icon_remove"] forState:UIControlStateNormal];
self.hasClearButtonAsRightView = YES;
now how to convert this to Swift?
or any ideas to workaround it?
You can add a custom button as right view of the UITextField like this
class CustomTextField : UITextField
{
override init(frame: CGRect) {
super.init(frame: frame)
let clearButton = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 15, height: 15))
clearButton.setImage(UIImage(named: "clear.png")!, forState: UIControlState.Normal)
self.rightView = clearButton
clearButton.addTarget(self, action: "clearClicked:", forControlEvents: .touchUpInside)
self.clearButtonMode = .never
self.rightViewMode = .always
}
func clearClicked(sender: UIButton)
{
self.text = ""
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Implementing a custom text field as suggested in the other answers is not a good idea. You should try to use extensions rather than inheritance if at all possible, because with inheritance you are much more likely to need to make major changes to your codebase in response to changes, whereas using extensions you are much more flexible to change.
I strongly suggest that instead of implementing a custom text field, you extend the UITextField class like this:
extension UITextField {
func applyCustomClearButton() {
clearButtonMode = .Never
rightViewMode = .WhileEditing
let clearButton = UIButton(frame: CGRectMake(0, 0, 16, 16))
clearButton.setImage(UIImage(name: "iCFieldClear")!, forState: .Normal)
clearButton.addTarget(self, action: "clearClicked:", forControlEvents: .TouchUpInside)
rightView = clearButton
}
func clearClicked(sender:UIButton) {
text = ""
}
}
Then to use it you just do this:
yourTextField.applyCustomClearButton()
Here is my solution in Swift 3. In addition to the already existing answer, I also made sure that both left and right views of the textfield (i.e. the search magnifier image view and the custom clear button) have a padding to their left/right by overriding leftViewRect() and rightViewRect(). Otherwise, they will stick right on the edges of the textfield.
class CustomTextField: UITextField
{
fileprivate let searchImageLength: CGFloat = 22
fileprivate let cancelButtonLength: CGFloat = 15
fileprivate let padding: CGFloat = 8
override init( frame: CGRect )
{
super.init( frame: frame )
self.customLayout()
}
required init?( coder aDecoder: NSCoder )
{
super.init( coder: aDecoder )
self.customLayout()
}
override func leftViewRect( forBounds bounds: CGRect ) -> CGRect
{
let x = self.padding
let y = ( bounds.size.height - self.searchImageLength ) / 2
let rightBounds = CGRect( x: x, y: y, width: self.searchImageLength, height: self.searchImageLength )
return rightBounds
}
override func rightViewRect( forBounds bounds: CGRect ) -> CGRect
{
let x = bounds.size.width - self.cancelButtonLength - self.padding
let y = ( bounds.size.height - self.cancelButtonLength ) / 2
let rightBounds = CGRect( x: x, y: y, width: self.cancelButtonLength, height: self.cancelButtonLength )
return rightBounds
}
fileprivate func customLayout()
{
// Add search icon on left side
let searchImageView = UIImageView()
searchImageView.contentMode = .scaleAspectFit
let searchIcon = UIImage( named: "search_magnifier" )
searchImageView.image = searchIcon
self.leftView = searchImageView
self.leftViewMode = .always
// Set custom clear button on right side
let clearButton = UIButton()
clearButton.setImage( UIImage( named: "search_cancel" ), for: .normal )
clearButton.contentMode = .scaleAspectFit
clearButton.addTarget( self, action: #selector( self.clearClicked ), for: .touchUpInside )
self.rightView = clearButton
self.clearButtonMode = .never
self.rightViewMode = .whileEditing
}
#objc fileprivate func clearClicked( sender: UIButton )
{
self.text = ""
}
}
with iOS 14, none of the solution were working for me. the clear button was getting wrong offset for different device sizes.
I had the image. if you dont have it, you can download it from SF Symbols. the name is xmark.circle.fill
In the end, I used this
let customClearButton = UIButton.appearance(whenContainedInInstancesOf: [UITextField.self])
customClearButton.setImage(UIImage(named: "icon-x"), for: .normal)
Updated to Swift 5, based on #marmoy answer:
public func addClearAllCustomButton() {
clearButtonMode = .never
rightViewMode = .whileEditing
let clearButton = UIButton(frame: rightViewRect(forBounds: bounds))
clearButton.setImage(UIImage(named: "clearAll"), for: .normal)
clearButton.addTarget(self, action: #selector(didTouchClearAllButton(sender:)), for: .touchUpInside)
rightView = clearButton
}
public func removeClearAllButton() {
rightViewMode = .never
}
#objc func didTouchClearAllButton(sender: UIButton) {
text = ""
}
For rigth padding & listen the clear delegate of textfield
class SearchBoxTextField: UITextField {
override open func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initialize() {
let clearButton = UIButton(frame: CGRect(x: 0, y: 0, width: 12, height: 12))
clearButton.setImage(UIImage(named: "removeIcon")!, for: .normal)
let clearView = UIView(frame: CGRect(x: 0, y: 0, width: 22, height: 12))
clearView.addSubview(clearButton)
self.rightView = clearView
clearButton.addTarget(self, action: #selector(clearClicked), for: .touchUpInside)
self.clearButtonMode = .never
self.rightViewMode = .whileEditing
}
#objc func clearClicked(sender:UIButton) {
self.text = ""
_ = self.delegate?.textFieldShouldClear?(self)
}
}

Resources