I am trying to change text of button button action. The font of the button not taken custom font. It will take default font. Please help on this issue I am enable to resolve this issue.
Heare is my code
#objc func moreAction(_ sender :UIButton) {
if fromBtn == "more"
{
fromBtn = "less"
sender.backgroundColor = .clear
sender.setTitle("- Less", for: .normal)
sender.titleLabel?.font = UIFont(name:"Lato-Bold",size:14)
index = sender.tag
tblView.reloadData()
}
else{
fromBtn = "more"
sender.backgroundColor = .clear
sender.setTitle("+ More", for: .normal)
sender.titleLabel?.font = UIFont(name:"Lato-Bold",size:14)
index = sender.tag
tblView.reloadData()
}
}
Thanking you in advance
Are you sure you added the font to xcode (here's the guide) and it matches the name?
It is also possible to reduce the number of repeated lines :)
fromBtn = fromBtn == "more" ? "more" : "less"
sender.backgroundColor = .clear
sender.setTitle(fromBtn == "more" ? "more" : "- Less", for: .normal)
sender.titleLabel?.font = UIFont(name:"Lato-Bold",size:14)
index = sender.tag
tblView.reloadData()
Related
I have a little issue with my segmented control. Sometimes when i swipe, the text color don't change on the selected segmented. I don't have this issue when i click to change segmented, only when i swipe.
Here, this is my code :
func setup() {
segmented.selectedSegmentIndex = 0
segmented.layer.backgroundColor = UIColor.background.cgColor
segmented.border.width = 2
segmented.border.color = .baseColor
segmented.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.baseColor], for: .selected)
segmented.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.baseColor], for: .normal)
segmented.addTarget(self, action: #selector(switchView(_:)), for: .valueChanged)
}
#objc func switchView(_ sender: UISegmentedControl) {
guard let views = self.views else { return }
views[currentIndex].hide()
currentIndex = sender.selectedSegmentIndex
views[currentIndex].show()
}
segmented 1
segmented 2 works
segmented 3 fail
in advance, thank you
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.
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
I have a scrollview inside a view. Inside the scrollview I create programmatically 5 buttons. Every button loads a different image with a different tag each one. I added a function that is called when pressing the buttons.
let avatarsListScrollingView = avatarsListView(CGSizeMake(70.0, 55.0), avatarCount: 5)
func avatarsListView(buttonSize:CGSize, avatarCount:Int) -> UIView {
**CODE**
for i in 0...(avatarCount-1) {
let button = UIButton(type: .Custom)
**CODE**
button.setImage(UIImage(named: avatarsList[i]), forState: .Normal)
button.tag = i
button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)
avatarButtonView.addSubview(button)
}
return avatarButtonView
}
Then when pressing the buttons, I call to "avatarListSelected":
func avatarListSelected(sender:UIButton){
if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
sender.setImage(image, forState: .Normal)
sender.tintColor = UIColor.redColor()
}
self.addAvatarView.reloadInputViews()
}
This function tints the image button to red, it is working fine, but the problem is that when I press some other button, I want the other one goes to the original color. Right now every button that I press gets in red.
I tried to add the call to "self.addAvatarView.reloadInputViews()" to try to "redraw" again all the buttons, but never gets called.
Do you guys know some way to do this?
Thanks to everybody!
This is the final code that solved the problem:
func avatarListSelected(sender:UIButton){
print(sender.tag)
if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
sender.setImage(image, forState: .Normal)
sender.tintColor = UIColor.redColor()
}
for view in self.avatarButtonView.subviews as [UIView] {
if let btn = view as? UIButton {
if btn.tag != sender.tag {
btn.setImage(UIImage(named: avatarsList[btn.tag]), forState: .Normal)
}
}
}
}
Create a property selectedButton: UIButton? and keep a reference to the selected button there. Don't forget to update it in avatarListSelected method and before you change it, if it isn't nil, change its color to original (and then change it).
If the buttons have different original colors, subclass UIButton class and keep the original color there.
I don't know if is better approach or answer, but, i maybe could delivery this using this approach:
Create a method that will "fill" the color for your choice button and "clear" color to others , but its a method that loop through UIScrollView and look for each UIButton. Something like this :
func setBackgroundColorButton(color:UIColor , buttonTag:Int){
for view in self.scrollView.subviews as [UIView] {
if let btn = view as? UIButton {
if btn == buttonTag {
btn.tintColor = color
} else {
btn.tintColor = UIColor.whiteColor()
}
}
}
}
This is the concept, i didn't tested, but maybe just need adjust to search inside your scroll view or similar.
But with this will be work nice i believe :D
You could do it like this
for i in 0...5 {
let button = UIButton(type: .Custom)
let x = 50 * i + 10
let y = 50
button.frame = CGRectMake(CGFloat(x), CGFloat(y), 40, 40)
button.setTitle("\(i)", forState: .Normal)
button.tag = i
button.backgroundColor = UIColor.greenColor()
button.tintColor = UIColor.blueColor()
button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func avatarListSelected(sender : UIButton){
sender.backgroundColor = UIColor.orangeColor()
for view in self.view.subviews{
if(view.isKindOfClass(UIButton)){
let button = view as! UIButton
if button.tag != sender.tag{
button.backgroundColor = UIColor.greenColor()
}
}
}
}
The frame etc is just for demonstation purpose only, you should of course use your own value. The tintColor property is not valid for all button types. Read the documentation for more information.
I UIButton using + buttonWithType:
What I need to figure out is how to manually change the button state. There are times when I need it to be set to "disabled."
I read through the UIButton documentation but I cannot seem to find anything about manually setting a button state.
Any thoughts would be greatly appreciated.
Did you try button.enabled = NO;?
Swift 5.0
button.isEnabled = false
there are also the states:
button.highlighted = NO;
button.selected = NO;
Objective C:
button.selected = Yes;
button.highlighted = NO;
button.enabled = Yes;
Swift 4:
button.isSelected = true
button.isEnabled = true
Also you can use:(swift 4)
if (button.state == .selected) {
//do something
}
You can manually set state of UIButton.
UIButton *btnCheck=[UIButton buttonWithType:UIButtonTypeCustom];
if(btncheck isselected])
{
btncheck.selected=FALSE;
}
else
{
btncheck.selected=TRUE;
}
You can do operation on UIButton as per your requirement like perform some action when UIButton is selected and while not selected.
Hope this will help you....
for Swift 3 you can use
button.isSelected = true
For anyone arriving here looking to change the 'state' of the button (as opposed to 'enabled'). Stephen is correct "This attribute is read only—there is no corresponding setter method."
What you really want to set is the state of the buttons cell.
[[myNSButtonOutlet cell] setState: NSOnState]; //Options NSOnState, NSOffState, NSMixedState
To accommodate the needs of setting a different button look when it's selected, set isSelected = true.
Here is an example of setting the state, and changing the UIButton appearance based on that state, using a quiz game environment:
if sender.titleLabel?.text == correctAnswer {
sender.isSelected = true
// Set title color and image based on 'selected' state.
sender.setTitleColor(.systemBlue, for: .selected)
sender.setImage(Utilities.sharedInstance.returnAnswerButtonImage(for: .correctlyAnswered).withRenderingMode(.alwaysOriginal), for: .selected)
sender.backgroundColor = .white
sender.tintColor = .systemBlue
// moveToNextQuestion()
} else {
sender.isSelected = true
sender.setTitleColor(.systemBlue, for: .selected)
sender.setImage(Utilities.sharedInstance.returnAnswerButtonImage(for: .incorrectlyAnswered).withRenderingMode(.alwaysOriginal), for: .selected)
sender.backgroundColor = .red
sender.tintColor = .systemBlue
}