Custom Clear Button - ios

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)
}
}

Related

Change lazy button opacity from outside of the class

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()
}
}

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:

Add a button on right view of UItextfield in such way that, text should not overlap the button

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()
}

Custom navigation bar items improperly placed

I have a custom navigation bar subclass:
class ProfileNavigationBar: UINavigationBar {
var titleLabel: UILabel
var backButton: UIBarButtonItem
var friendsButton: FriendsButton?
required init?(coder: NSCoder) {
titleLabel = UILabel(frame: CGRect(x: 0, y: 40, width: 320, height: 40))
backButton = UIBarButtonItem.backButton(nil, action: nil)
friendsButton = FriendsButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
super.init(coder: coder)
}
override func awakeFromNib() {
super.awakeFromNib()
let item = UINavigationItem()
item.titleView = titleLabel
item.leftBarButtonItem = backButton
item.hidesBackButton = true
let friendsItem = UIBarButtonItem(customView: friendsButton!)
item.rightBarButtonItems = [friendsItem]
pushItem(item, animated: false)
}
}
where the FriendsButton resizes itself when it's state property is changed.
Problem is that when the view is first loaded, it appears like this, with the back button and the FriendsButton right at the edge of the nav bar: (.loading state)
However, when I change the FriendsButton state to .add, it appears normally like this:
How can I fix this?
Here is the implementation of FriendsButton:
class FriendsButton: UIView {
var state: FriendsButtonState {
didSet {
style(selected: state)
}
}
var title: String = "" {
didSet {
set(title: title)
}
}
var font = UIFont.boldSystemFont(ofSize: 11)
private var imageView: UIImageView!
private var button: UIButton!
var loading: UIActivityIndicatorView!
init(frame: CGRect, state: FriendsButtonState = .loading) {
self.state = state
super.init(frame: frame)
backgroundColor = .yellow
let plusSize = frame.size.height/2
let plusYValue = (frame.size.height-plusSize)/2
imageView = UIImageView(frame: CGRect(x: plusYValue*2, y: plusYValue, width: plusSize, height: plusSize))
imageView.contentMode = .scaleAspectFit
addSubview(imageView)
let titleSize = (title as NSString).size(attributes: [NSFontAttributeName : font])
button = UIButton(frame: CGRect(x: plusYValue*3.5 + plusSize, y: 0, width: titleSize.width, height: frame.size.height))
addSubview(button)
loading = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loading.center = center
addSubview(loading)
style(selected: state)
updateSize()
}
func addTarget(object: Any, selector: Selector) {
button.addTarget(object, action: selector, for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func style(selected: FriendsButtonState) {
configureBorder(state: selected)
loading.startAnimating()
loading.isHidden = state != .loading
isHidden = false
switch state {
case .friends:
backgroundColor = .black
button.setTitleColor(.white, for: .normal)
imageView.image = #imageLiteral(resourceName: "friends-tick")
title = "Friends"
// ... + all other cases
}
self.updateSize()
}
private func configureBorder(state: FriendsButtonState) {
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = state == .loading ? 0 : 1
layer.cornerRadius = 5
}
private func set(title: String) {
let plusSize = frame.size.height/2
let plusYValue = (frame.size.height-plusSize)/2
let titleSize = (title as NSString).size(attributes: [NSFontAttributeName : font])
button.titleLabel?.font = font
button.setTitle(title, for: .normal)
button.frame = CGRect(x: plusYValue*3.5 + plusSize, y: 0, width: titleSize.width, height: frame.size.height)
self.updateSize()
}
private func updateSize() {
if state == .loading {
frame.size.width = frame.size.width
loading.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
loading.startAnimating()
return
}
let plusSize = frame.size.height/2
let plusYValue = (frame.size.height-plusSize)/2
let titleSize = (title as NSString).size(attributes: [NSFontAttributeName : font])
let totalWidth = plusYValue*5.5 + plusSize + titleSize.width
frame.size.width = totalWidth
}
EDIT: I have tried setting the button to the .add state initially but it would still appear at the very right of the nav bar until it was changed to the other state. It seems that the first state of the button always make the nav bar to shift all its children to the edge of the frame until it is updated.
EDIT: I wasn't able to reproduce the problem on another project by copying the relevant code, but this is the specific problem I am having (shown in the image below). The gap between the edge of the navigation bar and the back button is not maintained when first navigating to the view (I managed to get a screenshot midway through the navigation push animation). My question is now, what could be causing this?
You'll have to stop the activity indicator, otherwise it won't hide itself:
private func style(selected: FriendsButtonState) {
configureBorder(state: selected)
if (state == .loading) {
loading.startAnimating()
} else {
loading.stopAnimating()
}
loading.isHidden = state != .loading
Btw: You could also skip loading.isHidden = state != .loading if you configure the UIActivityIndicatorView as to hide itself when its stopped:
init(frame: CGRect, state: FriendsButtonState = .loading) {
// ...
loading = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loading.center = center
loading.hidesWhenStopped = true
addSubview(loading)
// ...
}
To lay out the right navigation bar button correctly, you have to modify FriendsButton.updateSize: When in state .loading - at least for the first time - you also have to update the frame.
private func updateSize() {
if state == .loading {
frame.size.width = frame.size.width
loading.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
loading.startAnimating()
// do not return here
}
let plusSize = frame.size.height/2
let plusYValue = (frame.size.height-plusSize)/2
let titleSize = (title as NSString).size(attributes: [NSFontAttributeName : font])
let totalWidth = plusYValue*5.5 + plusSize + titleSize.width
frame.size.width = totalWidth
}
I assume the same for the left button, but unfortunalty the your code does not compile here (get an error in the init? method when calling backButton = UIBarButtonItem.backButton(nil, action: nil), because there is no static member backButton on UIBarButtonItem
Now, it works on my machine:
Just after start of the app:
After state change to .friends
State changed back again to .loading
Everything is well aligned, no changes etc.
If this does not hold true for your project, than there might be other aspects that you didn't publish with your code.
You should update the frames of the subviews in layoutSubviews(), so you should override this method. The layoutSubviews() method is called whenever the frame changes and when the layout is flagged as being 'dirty' (by calling setNeedsLayout() you can achieve this).
It looks like you want to set the FriendsButtonState of the friendsButton in the init. Change:
friendsButton = FriendsButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
to
friendsButton = FriendsButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24), state:.add)

UITextfield leftView as overlay

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)
}

Resources