Xcode - Button Highlight Inconsistency - ios

I have a button that I create in interface builder that highlights the entire button on tap. I do nothing in code, simply ctrl+drag to my view controller file.
Then I have another button that I create programatically with this code.
let goToButton = UIButton()
goToButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
goToButton.titleLabel?.font = UIFont(name: "Arial", size: 18)
goToButton.setTitle("◀︎ Go To Form", forState: .Normal)
goToButton.backgroundColor = UIColor.whiteColor()
goToButton.showsTouchWhenHighlighted = true // Should highlight entire button?
but on tap it look like this.
How can I make it so that it matches the highlight like a button from interface builder

set your button type as Custom or `System and try once , change this
let goToButton = UIButton()
into
let goToButton = UIButton(type:.System)
or
let goToButton = UIButton(type:.Custom)
and hide this
goToButton.showsTouchWhenHighlighted = true

Related

Custom UIBarButtonItem added programmatically doesn't respect tintColor

In short, how can I change the color of the black button items (while maintaining control over their size)?
Longer version: I am programmatically adding a number of custom UIBarButtonItems to a UIToolbar. I'm using the solution found here so that I can control the size of the items.
While this fixes the UIBarButtonItem size issue, it does not respect tintColor like a typical UIBarButtonItem would. So I get something like this:
The large white item is the color I want, but not the size. This item was simply added in IB with the tintColor set to default.
The small black items are the size I want, and were added with the following code (N.B. the lines marked with // Not producing intented result):
for e in (self.profile?.expressions)! {
let button = UIButton()
button.setImage(UIImage(named: "emojiph"), for: .normal)
button.addTarget(self, action: #selector(onEmojiInsert), for: .touchUpInside)
let barItem = UIBarButtonItem(customView: button)
barItem.tag = e.family_expression_id
let wConstraint = barItem.customView?.widthAnchor.constraint(equalToConstant: 32)
wConstraint?.isActive = true
let hConstraint = barItem.customView?.heightAnchor.constraint(equalToConstant: 32)
hConstraint?.isActive = true
// Not producing intented result
button.tintColor = UIColor.white
// Not producing intented result
barItem.customView?.tintColor = UIColor.white
// Not producing intented result
barItem.tintColor = UIColor.white
self.emojibar.items?.append(barItem)
// Add flexible spacers
if (e.family_expression_id < (self.profile?.expressions.count)!) {
self.emojibar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
}
}
A workaround would be to provide the white image assets, but I'd prefer to find a more elegant solution if it exists.
To make the button change the color of the presented image to match the tint color then you need to initiate the button as a system type
let button = UIButton(type: .system)

How do I style the backBarButtonItem title in a navigation bar?

I'd like to be able to change only the text color of the back button in the navigation bar.
As a work around, I can sort of do what I'm trying to do by creating a custom view and assigning it to navigationItem.leftBarButtonItem, but it doesn't look very good and I also lose the swipe to pop ability.
Code for the above:
let button = UIButton(type: .system)
let originalImage = #imageLiteral(resourceName: "BackButton")
let scaledImage: UIImage = UIImage(cgImage: originalImage.cgImage!, scale: 30, orientation: originalImage.imageOrientation)
button.setImage(scaledImage, for: .normal)
button.setTitle("YourTitle", for: .normal)
button.sizeToFit()
button.setTitleColor(.brown, for: .normal)
button.tintColor = .blue
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
I also see things suggested like setting attributes of the back button via
navigationController?.navigationBar.topItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal)
but that doesn't seem to have any effect on the look of the text, despite
print("Attributes: ", navigationController?.navigationBar.topItem?.backBarButtonItem?.titleTextAttributes(for: .normal) ?? "No attributes")
resulting in Attributes: ["NSColor": UIExtendedSRGBColorSpace 1 0 0 1].
I could set tintColor but that would change the color of the back icon in addition to the title.
So what's the best way to do what I want? Is there a way?
Am not sure whether I understood you correctly. But try the below code. This will apply to all the bar button items of your app. Place this code where it is called only once though out app lifecycle. Like application: didFinishLaunchingWithOptions:
let attribs = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)]
UIBarButtonItem.appearance().setTitleTextAttributes(attribs, for: .normal)
I figured it out. You can style the back button by setting self.navigationItem.backBarButtonItem in the previous view controller.
For example, in my case I had TableViewController and when you clicked on a cell, the app would transition to ViewController. In TableViewController I had
public func changeColor() {
let barButton = UIBarButtonItem(title: "Anything", style: .plain, target: nil, action: nil)
barButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.brown], for: .normal)
self.navigationItem.backBarButtonItem = barButton
}
and then in ViewController I had
#IBAction func buttonPressed(_ sender: Any) {
let vc = self.navigationController?.viewControllers[0] as! TableViewController
vc.changeColor()
self.title = "hello very long title asdfasdfasfdasdfasdfasdfasdfasdf"
}
As a result, pressing a button in ViewController would change the color of the title of its back button to brown.

Use switch to change button image

I am trying to change the image on my button depending on the position of a switch. I am not sure how to do this. I am relatively new to code. I have managed to change the other things on the screen but not the button. I have attached my code. I put this function into the IBAction for the switch:
func updateMySwitchState(){
if darkModeSwitch.isOn {
self.view.backgroundColor = UIColor.black
removeAds.textColor = UIColor.white
aboutText.textColor = UIColor.white
about.textColor = UIColor.white
backButton.setImage(UIImage(named: "backinvert-40"), for: .normal)
} else {
self.view.backgroundColor = UIColor.white
removeAds.textColor = UIColor.black
aboutText.textColor = UIColor.black
about.textColor = UIColor.black
backButton.setImage(UIImage(named: "back-40"), for: .normal)
}
}
Did you connected the outlet of the button with the controller?
You can set both images button image in storyboard itself for normal & selected state respectively. After setting call
backButton.setSelected(true) for first image and
backButton.setSelected(false) for the second

creating customized popuser using label and buttons (swift/ios)

I'm trying to create custom popopview using labels and button, something like this;
First, created a label with opac background;
let opacLabel = UILabel(frame:CGRectMake(0,0,self.screenWidth,self.screenHeight))
opacLabel.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.9)
view.addSubview(opacLabel)
then a layer for popup view;
let categoryMenuLabel = UILabel(frame: CGRectMake(10,40,100,300))
categoryMenuLabel.backgroundColor = UIColor.whiteColor()
categoryMenuLabel.clipsToBounds = true
categoryMenuLabel.layer.cornerRadius = 7
and then a button
let saveButton = UIButton(frame: CGRectMake(spaceX,400,150,40))
saveButton.backgroundColor = UIColor.lightGrayColor()
saveButton.titleLabel!.font = UIFont(name: "Helvetia", size: 25)
saveButton.setTitle("Save", forState: UIControlState.Normal)
saveButton.addTarget(self, action: "categorySaveButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
categoryMenuLabel.addSubview(saveButton)
finally added categoryMenuLabel to main view and changed order;
self.view.addSubview(categoryMenuLabel)
self.view.bringSubviewToFront(opacLabel)
self.view.bringSubviewToFront(categoryMenuLabel)
With this configuration, when I try to press button, instead of button, it pressed the table cell under label.
I also couldn't manage to disable touch actions outside of the label.
Just enable user interaction on the label. It's off by default, and that prevents it's children from receiving any user interaction, as well:
categoryMenuLabel.userInteractionEnabled = true

Insert a button and load a second view programmatically using Swift

I want to, programmatically, add a button to a view and then when the user press this button a second view called "Giraanam" is loaded. I managed to write the code to display the button, but I cannot discover how to make it load the second view... Can anyone please help me?
The code I tried so far is:
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(20, 25, 34, 34)
button.backgroundColor = UIColor.greenColor()
button.setBackgroundImage(UIImage(named:"Back_Resultados.png"),forState: UIControlState.Normal)
button.addTarget(self, action: "Giraanam", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)
You need to implement function Giraanam to create a new view and add to another view. Example:
func Giraanam() {
let newView = UIView()
// customise your view
self.view.addSubview(newView)
}

Resources