Fill button icon when button pressed in swift - ios

I have a button with icon, I want when pressed button icon fill with color and when pressed again empty color and return to the previous state
Note: As much as possible I do not want to change icon after every pressed.

Here is example how you can achieve that, let me know if you don’t understand something.
class ViewController: UIViewController {
#IBOutlet weak var someBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
//Setting up images for normal and selected state.
func configureUI() {
let image = UIImage(named: "image")
let imageFilled = UIImage(named: "image-filled")
someBtn.setImage(image, for: .normal)
someBtn.setImage(imageFilled, for: .selected)
}
#IBAction func someBtnPressed(_ sender: Any) {
// Toggle basically makes someBtn’s selected state either true or false when pressed
someBtn.isSelected.toggle()
}
}

You can call setImage(_:for:) method to set the image of the button for a particular state.
The button is at the normal state when the user is not pressing it, so you should do:
yourButton.setImage(hollowHeart, for: .normal)
The button is at the highlighted state when the user is touching it, so you should do:
yourButton.setImage(filledHeart, for: .highlighted)
You just need to do this once after you create the button, probably in viewDidLoad.

Related

Change a UIButton's image that was created programmatically within a for loop Swift

I created a UIButton within a for-loop because the number of these button depend on a certain number in the database. However, I have to change the image of this button after it is clicked, which doesn't work.
What I have done is I tried holding an array of those buttons and trying to access the buttons like that, which I don't think is not working.
let buttonArray: [UIButton] = [UIButton]()
...extra code
for (index, num) in numberOfButtonsNeeded.enumerated() {
let button = UIButton()
button.tag = index
button.addTarget(self, action: #selector(self.tap(sender:)), for: .touchUpInside)
buttonArray.append(button)
}
...
#objc func tap(sender: UIButton) {
DispatchQueue.main.asnyc{
buttonArray[sender.tag].setImage(UIImage(named:"Somename"))
}
}
I can access the tap gesture but this button's image won't be reset. Is there a way I can access the button? I do not think this array works.
This is suspect:
#objc func tap(sender: UIButton) {
DispatchQueue.main.asnyc{
buttonArray[sender.tag].setImage(UIImage(named:"Somename"))
}
You are already on the main queue, and the sender is the button that was tapped. So you don't need the array.
#objc func tap(sender: UIButton) {
sender.setImage(UIImage(named:"Somename"))
}

how to add element using swift to a storyboard stackview

I am a beginner so sorry if it is a stupid question but I am trying to add new elements to a stack view that was made with a storyboard. I want to do it every time a button was pressed and I want the same color, size, constraint... how do I do this?
here is an image of my code
and this is the image of my storyboard structure
and this is what I made with the storyboard
and I want to add another button like the other ones every time the settings button is pressed
pls, can anyone help?
Connect your stack view to an #IBOutlet such as:
#IBOutlet var stackView: UIStackView!
Instead of trying to "copy" the button you designed in Storyboard, use a function to create a new button with your desired properties:
func makeNewButton() -> UIButton {
// create a button
let b = UIButton()
// set your desired font
b.titleLabel?.font = .systemFont(ofSize: 18.0, weight: .light)
// set background color to your desired light-green
b.backgroundColor = UIColor(red: 0.0, green: 0.85, blue: 0.0, alpha: 1.0)
// set title colors for normal and highlighted
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.gray, for: .highlighted)
return b
}
Now, your function for tapping the "Settings" button could look like this:
#IBAction func settingsButtonPressed(_ sender: Any) {
// call func that returns a new button with your
// desired colors, font, etc
let newButton = makeNewButton()
// set the title (presumably you'll be getting a new title string from somewhere)
newButton.setTitle("New Button", for: [])
// give it an action
newButton.addTarget(self, action: #selector(self.btnTapped(_:)), for: .touchUpInside)
// add it to the stack view
stackView.addArrangedSubview(newButton)
}
Edit the above code assumed an existing function for handling the button action - such as:
#objc func btnTapped(_ sender: UIButton) {
// do something when the button is tapped
print("A button was tapped...")
}

how to change UI Button shape programmatically?

I have a button that contains a finger print image like the picture above. that fingerPrint button has a function to segue to viewController2. that fingerPrint button exists on the viewController1.
when the viewController1 is opened for the first time, I will get a data from the server, if I don't have that data, I shouldn't segue to viewController2 .
but sometimes we have an error as the response of my request. if I get the error response, then I want that finger button to be rectangular button that has 'Refresh' as the title and has different function to make request again to the server
how to achieve change the shape of existing UI Button?
class ViewController1 : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getDataFromServer()
}
#IBAction func fingerPrintButtonDidPressed(_ sender: Any) {
}
func getDataFromServer() {
// send request to get data from server
}
}
It is usually best to do it either all in code or all in storyboard. To do it in storyboard I suggest one of the following:
Create 2 buttons and in code hide one or another depending on your state
Assign different images and texts for different button states (there is a dropdown in interface builder) and then change the state of a button in runtime
To do it in code overall I suggest simply changing the values.
Assume you have something like this:
enum ViewState {
case idle
case success
case failed
}
var state: ViewState = .idle {
didSet {
refreshButton()
}
}
Now you can set your state when you get a response or on any event needed. All you need to implement is refreshButton.
func refreshButton() {
switch state {
case .idle:
button.setTitle(nil, for: .normal)
button.setImage(fingerprintImage, for: .normal)
button.backgroundColor = .clear
case .success:
button.setTitle(nil, for: .normal)
button.setImage(fingerprintImage, for: .normal)
button.backgroundColor = .clear
case .failed:
button.setTitle("REFRESH", for: .normal)
button.setImage(nil, for: .normal)
button.backgroundColor = .green
}
}
You can then use the same switch inside your button action (on press).
if isError
{
button.type = .system
button.backgroundColor - UIColor.green
button.setTitle("REFRESH" for: .normal)
button.addTarget(--------)
}
else
{
button.type = .custom
button.setImage(UIImage(named: "yourImageName.png") for: .normal)
button.addTarget(--------)
}
Simple Solution is : Use two buttons one for figure Image second for Refresh text. And use button isHidden property vice-versa.
For Auto layout
If you are using Auto layout then use constraint IBOutlet and change it's constant property value. it will change your button height or width.
For Auto resize
if you are using Auto resize than you can change you button frame which you want

Implementing UIButtons for selection in Swift

I'm new to iOS development and I'm working on a Fire Safety App. I would like to give the user the option of 3 risk levels: Low, Medium and High by using (I suppose) 3 UIButtons which the user can tap, and which ever one they tap would turn a certain colour.
I've managed to get 3 UIButtons working, and they can change colour when tapped but if I tap another I can't get the previous button to change back and I've had difficulties getting a value for them (For example when submitted if the user pressed Low I would use the number 2 for calculations)
To show this I did a quick drawing:
Button Example
Thanks for your help :)
==== EDIT ====
I am now using a Segmented Control instead of UIButtons to do this. But I need to know how to use them in an if statement
#IBOutlet var RiskChoice: UISegmentedControl!
#IBOutlet var ValueLabel: UILabel!
#IBOutlet var CalcButton: UIButton!
#IBAction func Calculate(sender: UIButton) {
if (RiskChoice.selectedSegmentIndex == 0){
ValueLabel.text = String("Low")
}
Nothing appears in the Label I have set up.. Could someone direct me here?
You can just reset all the 3 buttons to their default state when any of the button is tapped and then highlight the current button.
#IBAction func buttonClicked(sender: UIButton) {
/** Reset all button to default state*/
resetAllButtons()
/** Highlight current button */
sender.backgroundColor = UIColor.redColor()
sender.titleColor = UIColor.whiteColor()
}
private func resetAllButtons() {
button1.backgroundColor = UIColor.clearColor()
button1.titleColor = UIColor.blackColor() /// Or use this : button1.setTitleColor(UIColor.blackColor, forState: .Normal)
button2.backgroundColor = UIColor.clearColor()
button2.titleColor = UIColor.blackColor()
button3.backgroundColor = UIColor.clearColor()
button3.titleColor = UIColor.blackColor()
}

Swift - Change color and size of text when UIButton is tapped

Basically, I have a three buttons on my main screen.
When I select one of these buttons, I would like the text on the selected button to change to bold and change color (blue).
When I select a different button, I would like the newly selected button to change to bold and change color(blue), and the previously selected button to go back to normal. (non-bold and black text)
I have these buttons sending an action to the script.
This is what I have, I can't seem to get it to work. Help would be much appreciated!
#IBAction func buttonOne(sender: UIButton){
sender.setTitleColor(UIColor.blueColor(), forState: UIControlState.Highlighted)
}
I have tried .Highlighted and .Selected on the UIControlState, neither seem to work. I have also tried the following, but I cant get it to work.
#IBAction func buttonOne(sender: UIButton){
sender.titleLabel?.textColor = UIColor.blueColor()
}
I figured that since the sender was a UIButton, and it was the button that was clicked, taking the values off of it and resetting them would work. I do believe I am missing something.
Thank you
Sounds like you want UIControlState.Normal
Selected does nothing in most cases, and Highlighted is only while you're pressing the button.
See more info here: https://developer.apple.com/library/ios/documentation/uikit/reference/uicontrol_class/index.html#//apple_ref/doc/constant_group/Control_State
Maybe you can do with a transform...
#IBAction func buttonPressed(sender: UIButton) {
sender.titleLabel!.textColor = UIColor.blueColor()
sender.transform = CGAffineTransformMakeScale(0.8, 0.8)
}
#IBAction func buttonReleased(sender: UIButton) {
sender.titleLabel!.textColor = UIColor.redColor()
sender.transform = CGAffineTransformIdentity
}
Provide tags to all buttons, connect each button actions to same function and try the following code:
#IBAction func butnClicked (sender : UIButton) {
for tg in 1...2 {
print(sender.tag)
let tmpButton = self.view.viewWithTag(tg) as? UIButton
if tmpButton?.tag == sender.tag {
tmpButton?.setTitleColor(.red, for: .normal)
} else {
tmpButton?.setTitleColor(.gray, for: .normal)
}
}
Hope will be helping.

Resources