I'm trying to add an "error message" bubble that appears on top of the textfield when a user inputs incorrect values. I've been using the .leftView property which works fine, however it takes up "space" in the textField, pushing content to the right. What is the best way to display the leftView as an "overlay" rather than in the field itself? (i.e. remove it's bounds)
class ValidatedTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
// Defaults
maxLength = 40
layer.sublayerTransform = CATransform3DMakeTranslation(leftPadding, 0, 0)
backgroundColor = UIColor.whiteColor()
// Listen in on own text input
self.addTarget(self, action: "textHasChanged", forControlEvents: UIControlEvents.EditingChanged)
self.addTarget(self, action: "checkTextValid", forControlEvents: UIControlEvents.EditingDidEnd)
}
override func layoutSubviews() {
super.layoutSubviews()
// Add error label message
labelMessage.frame = CGRectMake(10-leftPadding, -10, self.bounds.size.width-20, 24)
labelMessage.backgroundColor = .blackColor()
labelMessage.text = "Message goes here"
labelMessage.font = UIFont.boldSystemFontOfSize(16)
labelMessage.textColor = .whiteColor()
labelMessage.textAlignment = .Center
labelMessage.layer.cornerRadius = 8
self.leftView = labelMessage
self.leftViewMode = .Always
}
}
So I think I've figured it out. By using leftViewRectForBounds and returning a zero CGRect I'm able to eliminate it's physical presence.
override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: 0, height: 0)
}
Related
I want the height of custom inputView of the textView to be same height as that of default keyboard. I tried a lot, including:
self.textView.inputView?.autoresizingMask = .flexibleHeight
I couldn't find a solution. It's always coming less than that of default keyboard. (EDIT: This issue exists only for iPhone X)
My code:
class ViewController: UIViewController {
let textView = UITextView()
let button = UIButton()
var keyboardView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
textView.backgroundColor = .lightGray
button.backgroundColor = .red
self.view.addSubview(textView)
self.view.addSubview(button)
}
#objc func buttonAction() {
if self.textView.inputView == nil {
self.textView.inputView = keyboardView
self.textView.inputView?.autoresizingMask = .flexibleHeight
self.textView.reloadInputViews()
} else {
self.textView.inputView = nil
self.textView.reloadInputViews()
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
textView.frame = CGRect(x: 0, y: 50, width: self.view.frame.size.width - 50, height: 50)
button.frame = CGRect(x: self.view.frame.size.width - 50, y: 50, width: 50, height: 50)
}
}
I've added a search bar to my navigation.titleView
self.navigationItem.titleView = searchBar
There's also a BackBarButtonItem with title = ""
self.navigationItem.backBarButtonItem?.title = ""
But then there're gap between Back Button and SearchBar, like this:
I Think that the gap appears here because there's space for title of backBarButtonItem (because my title is null "" but the space still there)
So I want to ask how to omit that gap? I want to make my searchBar nearer my backBarIcon
Thank you so much!
EDIT 1:
I try to change searchBar's frame but it's not working
This is my code
//Change searchBar's frame
let titleViewFrame = (searchController.searchBar.frame)
searchController.searchBar.frame = CGRect(x: titleViewFrame.minX - 20.0, y: titleViewFrame.minY, width: titleViewFrame.width + 20.0, height: titleViewFrame.height)
override func viewDidLoad() {
super.viewDidLoad()
let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 22))
let searchBar = UISearchBar()
searchBar.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(searchBar)
let leftButtonWidth: CGFloat = 35 // left padding
let rightButtonWidth: CGFloat = 75 // right padding
let width = view.frame.width - leftButtonWidth - rightButtonWidth
let offset = (rightButtonWidth - leftButtonWidth) / 2
NSLayoutConstraint.activate([
searchBar.topAnchor.constraint(equalTo: container.topAnchor),
searchBar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
searchBar.centerXAnchor.constraint(equalTo: container.centerXAnchor, constant: -offset),
searchBar.widthAnchor.constraint(equalToConstant: width)
])
self.navigationItem.titleView = container
}
You can't do that, there is a default space given which we cannot change if we have back button.
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back")
self.navigationController?.navigationBar.tintColor = UIColor.lightGray
Below is the screenshot
class SearchBarContainerView: UIView {
let searchBar: UISearchBar
init(customSearchBar: UISearchBar) {
searchBar = customSearchBar
super.init(frame: CGRect.zero)
addSubview(searchBar)
}
override convenience init(frame: CGRect) {
self.init(customSearchBar: UISearchBar())
self.frame = frame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
searchBar.frame = bounds
}
}
class MyViewController: UIViewController {
func setupNavigationBar() {
let searchBar = UISearchBar()
let searchBarContainer = SearchBarContainerView(customSearchBar: searchBar)
searchBarContainer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)
navigationItem.titleView = searchBarContainer
}
}
I can add a button to a textfield on the right hand side of the UITextField using the right view however, the text overlaps on the button. Below is the code for right view button
UIView.commitAnimations()
var btnColor = UIButton(type: .Custom)
btnColor.addTarget(self, action: #selector(self.openEmoji), forControlEvents: .TouchUpInside)
btnColor.frame = CGRect(x: CGFloat(textField.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
btnColor.setBackgroundImage(UIImage(named: "send.png"), forState: .Normal)
textField.addSubview(btnColor)
Please let me know how to give padding from right view for text.
use the rightView property of the UITextField. Basically, there are two properties (this one and leftView accordingly) that allow you to place custom views/controls inside the UITextField. You can control whether those views are shown or not by means of rightViewMode/leftViewMode properties:
textField.rightView = btnColor
textField.rightViewMode = .unlessEditing
for e.g
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "send.png"), for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0)
button.frame = CGRect(x: CGFloat(txt.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
button.addTarget(self, action: #selector(self.refresh), for: .touchUpInside)
textField.rightView = button
textField.rightViewMode = .always
and call the action as
#IBAction func refresh(_ sender: Any) {
}
Create UITextField extension and add below method in it and you can change UIButton code as per your requirement.
func setRightViewIcon(icon: UIImage) {
let btnView = UIButton(frame: CGRect(x: 0, y: 0, width: ((self.frame.height) * 0.70), height: ((self.frame.height) * 0.70)))
btnView.setImage(icon, for: .normal)
btnView.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 3)
self.rightViewMode = .always
self.rightView = btnView
}
Correct answer Swift3+
If you just override the methods, the text may overlap the right view. This code completely solves this problem.
You UITextField subclass:
//...
private func setInsets(forBounds bounds: CGRect) -> CGRect {
var totalInsets = insets //property in you subClass
if let leftView = leftView { totalInsets.left += leftView.frame.origin.x }
if let rightView = rightView { totalInsets.right += rightView.bounds.size.width }
return UIEdgeInsetsInsetRect(bounds, totalInsets)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return setInsets(forBounds: bounds)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return setInsets(forBounds: bounds)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return setInsets(forBounds: bounds)
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.rightViewRect(forBounds: bounds)
rect.origin.x -= insets.right
return rect
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.leftViewRect(forBounds: bounds)
rect.origin.x += insets.left
return rect
}
you can assign button at right view of textfield
var btnColor = UIButton(type: .Custom)
btnColor.addTarget(self, action: #selector(self.openEmoji), forControlEvents: .TouchUpInside)
btnColor.frame = CGRect(x: CGFloat(textField.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
btnColor.setBackgroundImage(UIImage(named: "send.png"), forState: .Normal)
textField.rightView = btnColor
internal var btnDropDown: UIButton {
let size: CGFloat = 25.0
let button = UIButton(type: .custom)
button.setImage(#imageLiteral(resourceName: "DropDownImage"), for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -(size/2.0), 0, 0)
button.frame = CGRect(x: self.frame.size.width - size, y: 0.0, width: size, height: size)
return button
}
And I used it like this:
override func awakeFromNib() {
super.awakeFromNib()
textField.rightView = self.btnDropDown
textField.rightViewMode = .always
}
You can achieve same as shown below:
#IBOutlet weak var textField: UITextField!
var textFieldBtn: UIButton {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "image.png"), for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
button.frame = CGRect(x: CGFloat(textField.frame.size.width - 40), y: CGFloat(5), width: CGFloat(40), height: CGFloat(30))
button.backgroundColor = UIColor.darkGray
button.addTarget(self, action: #selector(self.refreshContent), for: .touchUpInside)
return button
}
func refreshContent() {
// Add your code here to handle button.
}
Add to textField.
textField.rightView = textFieldBtn
textField.rightViewMode = .always
For Swift4
func setupUI() {
let imgSearch = UIImageView();
let imgSearch = UIImage(named: "search");
// set frame on image before adding it to the uitextfield
imgSearch.image = imagePassword;
imgSearch.frame = CGRect(x: txtSearchField.frame.size.width - 40 , y: 5, width: 22, height: 22)
txtSearchField.rightView = imgSearch
txtSearchField.rightViewMode = .always
}
Call function like this
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
I am trying to access the MyCustomView from another class using the following code in ViewController.swift ..
var view = MyCustomView(frame: CGRectZero)
.. in the viewDidLoad method. The problem is the view does not get initialized in the simulator.
I have already set class in storyboard for the current ViewController.
class MyCustomView: UIView {
var label: UILabel = UILabel()
var myNames = ["dipen","laxu","anis","aakash","santosh","raaa","ggdds","house"]
override init(){
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView() {
label.frame = CGRectMake(50, 10, 200, 100)
label.backgroundColor=UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
label.hidden=true
self.addSubview(label)
var btn: UIButton = UIButton()
btn.frame=CGRectMake(50, 120, 200, 100)
btn.backgroundColor=UIColor.redColor()
btn.setTitle("button", forState: UIControlState.Normal)
btn.addTarget(self, action: "changeLabel", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn)
var txtField : UITextField = UITextField()
txtField.frame = CGRectMake(50, 250, 100,50)
txtField.backgroundColor = UIColor.grayColor()
self.addSubview(txtField)
}
The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.
Swift 3 / Swift 4 Update:
let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)
var customView = UIView()
#IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)
view = MyCustomView(frame: CGRectZero)
In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.
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)
}
}