How to change UIButton text - uibutton

When writing apps for iOS you can simply change the text of a UIButton by writing:
variable.text = ("")
However, with tvOS you cannot write .text and I was wondering if anyone knew how you could do it.

To change the text/title of a UIButton you need to use setTitle:forState:.
Objective C:
[myButton setTitle:#"A New Title" forState:UIControlStateNormal];
Swift:
myButton.setTitle("A New Title", forState: .Normal)
UIButton Class Reference

Related

Text color in UIMenuController affected by UIButton appearance setting

I've observed following:
By setting the Titlecolor of a UIButton with appearance, the UIMenuItems in a UIMenuController of a UITextView are getting the same color.
Code in applicationDidFinishLaunching:
[[UIButton appearance] setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
My question:
Is there a way to suppress it
or
give a UIMenuItems another color?
What i have tried:
With appearanceWhenContainedIn UITextview
I've tried to set the appearance for buttons contained in TextViews with
[UIButton appearanceWhenContainedIn:[UITextView class], nil]
But this obviously didn't work since the UIMenuController is not inside the TextView.
With appearanceWhenContainedIn UIMenuController/UIMenuItem
Is not possible, since both are not implementing the UIAppearanceContainer protocol.
I found 2 ways to fix this issue.
Here is a screenshot of the result of the following solutions :
First solution
The UIMenuController is not contained in the View Controller views hierarchy. You can thus define your UIButton color that way (instead of setting the global Button appearance) :
Swift :
UIButton.appearanceWhenContainedInInstancesOfClasses([UIViewController.self]).setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
Objective-C :
[[UIButton appearanceWhenContainedInInstancesOfClasses:#[UIViewController.class]] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
That solution works for most of the cases. But if you use the delete button or actions button of Table View Cells it will also take the set color and you won't be able to change that color through appearance proxy.
Second solution (my preferred one)
The second solution uses directly the private UIButton subclass class name used by Apple in the Menu Controller.
I would never recommend to access a private Apple class (and furthermore through its name), but in that specific Menu Controller color customization case I think that's the best solution. It lets you define the clean way your view appearances.
Swift :
Define your global Button title color appearance :
UIButton.appearance().setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
Specific exception for the MenuController :
(NSClassFromString("UICalloutBarButton")! as! UIButton.Type).appearance().setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
Objective-C :
Define your global Button title color appearance :
[[UIButton appearance] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
Specific exception for the MenuController :
[[NSClassFromString(#"UICalloutBarButton") appearance] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

How to customize the calloutAccessoryView of a MKAnnotationView under iOS7?

Under iOS6 I did the following to set a custom image for the button of the right callout accessory view:
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setImage:[UIImage imageNamed:#"detaildisclosurebutton.png"] forState:UIControlStateNormal];
annotationView.rightCalloutAccessoryView = rightButton;
That worked very well. Now I am updating the App to iOS7 and I just get a blue circle:
When I replace the image with a square image, it becomes a square. But it is blue too.
Seems to be the tintColor. I tried to set it to nil. I also tried to use buttonWithType:UIButtonTypeCustom as buttonType, but no success.
Has anyone a solution for it?
Button type UIButtonTypeDetailDisclosure tints the image by default. Use UIButtonTypeCustom instead.
If you really need UIButtonTypeDetailDisclosure (and I can't think of a reason why you would given that you're setting a custom image, you can force your image to use "always original" rendering mode:
[[UIImage imageNamed:#"detaildisclosurebutton.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]

Setting UIButton image results in blue button in iOS 7

On iOS 6 SDK I wrote the following lines of code to display an image inside a button:
NSURL *thumbURL2 = [NSURL URLWithString:#"http://example.com/thumbs/2.jpg"];
NSData *thumbData2 = [NSData dataWithContentsOfURL:thumbURL2];
UIImage *thumb2 = [UIImage imageWithData:thumbData2];
[btn2 setImage:thumb2 forState:UIControlStateNormal];
[self.view addSubview:btn2];
But now with Xcode 5 and iOS 7 this doesn't work. The button doesn't contain the image. The button is filled with blue color.
In iOS7 there is new button type called UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button
Check your .xib file and change button type to Custom
To do this programmatically, add this line to the viewDidLoad:
[UIButton buttonWithType:UIButtonTypeSystem];
It seems iOS 7 is using the image provided just as an Alpha mask for displaying the button's tint color.
Changing the button type to UIButtonTypeCustom did the trick for me (thanks user716216!).
Setting the image as background doesn't always work if you already have a background image, as was my case.
Swift 3, 4, 5 :
let image = UIImage(named: "my-image")
myButton.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
There's a good chance that the image is there and you just can't see it. Try changing the button's type to UIButtonTypeCustom. If that doesn't work, set the button's background color to [UIColor clearColor];
For swift:
let aButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
The issue is the TintColor. By default, iOS throws a blue tint color over every button. You can get around it through 3 ways.
Change the tint color. [button setTintColor:[UIColor blackColor]];
This may color your image in ways you don't want it to.
As most other suggested, set the background image. [button setBackgroundImage:[UIImage...]];
Add an UIImageView to your button.
UIImageView * img = [[UIImageView alloc] initWithImage:[UIImage...]];
[button addSubView:img];
I had the same issue.
On my storyboard I had a button without any image.
I would then assign the image in the code.
IOS 7 came and I got a lot of blue images.
The resolution was simple yet confusing. If I assign any image on the storyboard and then change the image at run time it works fine.
You always must specify a starting image on the storyboard even if you are not going to use it.
This worked for me
[myButton1 setBackgroundImage:[UIImage imageNamed:#"phones.png"] forState:UIControlStateNormal];
Note:Remove front image before doing this.
Old thread, but I wanted to chime in because I just had the same problem. The issue was just that you are calling setImage when you should call setBackgroundImage.
In iOS 13 -- just set the Tint property to White, while keeping the type of the UIButton as Custom
None of the given solutions were working for me. If you do not set an initial image in Storyboard, you can still change the image of the button by using setBackgroundImage.
For your example, only a minor change is needed.
NSURL *thumbURL2 = [NSURL URLWithString:#"http://example.com/thumbs/2.jpg"];
NSData *thumbData2 = [NSData dataWithContentsOfURL:thumbURL2];
UIImage *thumb2 = [UIImage imageWithData:thumbData2];
[btn2 setBackgroundImage:thumb2 forState:UIControlStateNormal];
[self.view addSubview:btn2];
This Problem is called blue color problem of the button in xcode.
When we make button by code the button shows the blue tint color by default.This can be solved byt assigning tint color to black or white accordingly to your cell's color.
The code is :
UIImage *closebtnimg = [UIImage imageNamed:#"icon_uncheck.png"];
UIImage *closebtnimg1 = [UIImage imageNamed:#"icon_checked.png"];
Custombutton *button = [Custombutton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(52, 66, 25, 24)];
[button setBackgroundImage:closebtnimg forState:UIControlStateNormal];
[button setBackgroundImage:closebtnimg1 forState:UIControlStateSelected];
[button setTintColor:[UIColor whiteColor]];
[cell.contentView addSubview:button];
[button addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];
Using Xcode 9.2 none of the above solutions worked for what I was looking for.
I was looking for a solution that will let me set .normal and .selected UIControlState images inside the storyboard for their original rendering mode, but, inside the Swift file, no string literals should exist regarding the image names.
Basically, inside your code you will get the image you set inside your storyboard for .normal state and re-render it as .alwaysOriginal (Same for .selected state), then, you will set that image (which is now rendered as original and won't be affected by the tint) for the relevant state (.normal and .selected) of your UIButton.
Here it is:
// Get your .normal image (you set via your storyboard) and render it as original
let unselectedImage = yourButton.image(for: .normal)?.withRenderingMode(.alwaysOriginal)
// Set your normal image but this time rendered as original
yourButton.setImage(unselectedImage, for: .normal)
// Same for selected state
let selectedImage = yourButton.image(for: .selected)?.withRenderingMode(.alwaysOriginal)
yourButton.setImage(selectedImage, for: .selected)
This way you can set your button image states and if the image name will change, it won't affect your code.
making the tint color as clearcolor for all the four states(Default,Highlighted,selected,disabled) worked for me.
In Swift 4, initialize your UIButton and assign uyour image Data as follows:
let myButton = UIButton(type: .cutsom)
myButton.setImage(UIImage(data:myImageData), for: .normal)

Custom UITextField clear button

Is it possible to customize the image of the clear button in a UITextField? I have a dark textfield background and the "x" is not visible enough.
You can set your own custom clear button to the text field's rightView property. Make sure set the rightViewMode property to UITextFieldViewModeWhileEditing or UITextFieldViewModeAlways, whatever makes sense for your case.
If the button's position isn't right for your need, you can subclass UITextField and override the rightViewRectForBounds: method.
The documentation says the default for the clearButtonMode property is UITextFieldViewModeNever, but I suspect Interface Builder may set it to UITextFieldViewModeWhileEditing - Make sure you set it to the "never" value so it doesn't appear.
All these properties are documented in UITextField Class Reference.
You can access that property using KVO:
UIButton *clearButton = [myTextField valueForKey:#"_clearButton"];
[clearButton setImage:[UIImage new] forState:UIControlStateNormal];
Tested iOS7.0 - 8.4
It is possible to update the backgroundImage of all clear buttons using the following UIAppearance method. Unfortunately you cannot update the image of the button:
UIButton *defaultClearButton = [UIButton appearanceWhenContainedIn:[UITextField class], nil];
[defaultClearButton setBackgroundImage:[UIImage imageNamed:#"clearButtonBkg1.png"] forState:UIControlStateNormal];
Using the following images, this results in the following clear button:
White background image #3x:
Note: This will update the background image of ALL buttons contained in textfields
Swift 2.2+ / iOS 9+ version of #Brody Robertson's answer:
let defaultClearButton = UIButton.appearanceWhenContainedInInstancesOfClasses([UITextField.self])
defaultClearButton.setBackgroundImage(UIImage(named: "ClearIcon"), forState: UIControlState.Normal)
Swift 3
let customClearButton = UIButton.appearance(whenContainedInInstancesOf: [UITextField.self])
customClearButton.setBackgroundImage(UIImage(named: "custom_cb"), for: .normal)
depends on #Tuss László's answer
Swift 3.0
myTextField.clearButtonMode = .whileEditing
if let clearButton = myTextField.value(forKeyPath: "_clearButton") as? UIButton {
clearButton.setImage(UIImage(named:"myImage"), for: .normal)
clearButton.setImage(UIImage(named:"myImage"), for: .highlighted)
}
But really use it carefully. If Apple change implementations in future iOS releases, it would not be work
One approach would be to create a custom UITextField that has your desired image as a subview and clears the parent text field when tapped. You disable the default button and add your custom behavior in this custom text field.
This should get you started. If there are any more concrete questions, feel free to edit your question or comment here if it's a minor problem.

Choosing a button with a variable

I have this working in C#, but don't know where to go with Objective C (Xcode specifically).
I have 8 buttons
Stack1, Stack2, etc.
I want to choose Stack(variable) and change the image.
In C# I used
Button Stacks = this.Controls["Stack" + StackNumber.ToString()] as Button;
Stacks.BackgroundImage = .....
Can I do this in Objective C also?
I hope I understand your question correctly. You want to change button's image by clicking on another button. You can assign tag property to your different buttons like stack1.tag = 1001; , stack2.tag = 1002; , stack3.tag = 1003;
Now in your button click method :
- (IBAction)buttonStack1Click:(id)sender // for stack1 button
{
UIButton *tempStack = (UIButton *)[self.view viewWithTag:1003]; //to change image of stack3 button
// Now change the image of stack3 button
[tempStack setImage:[UIImage imageNamed:#"su.png"] forState:UIControlStateNormal];
}
Hope it gives an idea...
Take help of for loop and implement the code below :
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Any query arises,you can tell me.. hope that helps you.
If you want to perform certain function when a button is clicked then there are two ways..
One is Sarah way:Creating Button programmatically
The Other ways is if you are designing buttons in your interface builder :
Then :
1) Make those Buttons an IBOutlet..Also Make IBAction(Lots of tutorials available online..google them)
2) The IBAction will be something like this : - (IBAction)StackButton(YourNumber)Clicked:(id)sender {
In that function change the image of the button you want.
Like
[StackButton1 setImage:MyImage forState: UIControlStateNormal];