I am working on an app which has a button. The button has no text, image or background.
So what I want to do is to give it an image in the viewDidLoad function.
This is what I have:
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage("redTap.png", forState: UIControlState.Normal)
}
But I have an error that says I can not convert string to UIIMage.
How do I get it to work?
I have tried:
let image = UIImage(named: "redTap.png")
tapButton.setImage(image, forState: UIControlState.Normal)
I have gotten it to work but now I have a problem.
The image is suppose to be a red text but it shows up blue.
I was able to get the image to show correctly by using:
let image = UIImage(named: imageColor[randNum])?.imageWithRenderingMode(.AlwaysOriginal)
tapButton.setImage(image, forState: UIControlState.Normal)
What I want now is to not have the button be highlighted when the button is pressed. I have a few other buttons that have images assigned to them in xcode and not through code. They don't highlight when pressed.
So how can I get rid of highlighting when the button is pressed?
You don't need ".png".
If ".imageWithRenderingMode(.AlwaysOriginal)" is working for you: To keep the same image in different states, you have to set the same image/properties for the different states.
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)
}
Swift 3
yourBtn.setImage( UIImage.init(named: "imagename"), for: .normal)
now (swift 3 edition):
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
}
First I would put the image you wanted inside the Assets.xcassets folder. Just drag it in. Then you can call it whatever you want by double-clicking on it. Lets say that it is called "redTap".
For code you would put:
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let redTapImage = UIImage(named: "redTap")
tapButton.setImage(redTapImage, forState: UIControlState.Normal)
}
There's one simple solution:
#IBOutlet var tapButton: UIButton!{
didSet{
let image = UIImage(named: imageColor[randNum])
tapButton.setImage(image, forState: UIControlState.Normal)
}
Besides that, in the Attribute Inspector, Set Button type to 'Custom'
First set your button type as Custom in interface builder and set the image for normal state for your button.
Connect IBOutlet for button in class file as
#IBOutlet weak var btnCheckbox: UIButton!
in your class file in viewDidLoad set image for selected state as
btnCheckbox.setImage(UIImage.init(named: "name_of_image"), for: .selected)
Create #IBAction for in class file as
#IBAction func onTapCheckBox(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
Then connect #IBAction to your button's Touch up Inside event from interface builder
Let image = UIImage(named : "redTap.png")
tapButton.setImage(image, .Normal)
let button = UIButton(type: .Custom)
let image = UIImage(named:"redTap")?.imageWithRenderingMode(.AlwaysTemplate)
button.setImage(image, forState: .Normal)
button.tintColor = UIColor.redColor()
Update For latest swift versions,
It works this way
button.setImage(UIImage(named: "propopup")?.withRenderingMode(.alwaysOriginal), for: [])
Related
I want to change the background and text of the button on click, I tried several SO solutions but they haven't worked, you can see what I tried in my project:
https://github.com/jzhang172/modalTest
I tried debugging it by putting a simple print statement and it looks like it doesn't ever go to it.
UIButton's have a method for setting the title color. So if you had a UIButton IBOutlet named myBtn:
myBtn.setTitleColor(UIColor.blackColor(), forState: .Highlighted)
and to change the text of the button on touch:
myBtn.setTitle("This button was touched", forState: .Highlighted)
As far as setting the background color, you could add an extension for your UIButton which allows you to do this:
extension UIButton {
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
self.setBackgroundImage(imageWithColor(color), forState: state)
}
}
Then you could do:
myBtn.setBackgroundColor(UIColor.grayColor(), forUIControlState: .Highlighted)
Hope this helps!
SOLUTION:
1) Create an IBAction from your UIButton and also an IBOutlet called button.
EDIT: As per your request (How to trigger the even when the button is TOUCHED, not RELEASED?):
2) Do this:
#IBAction func changes (sender: UIButton) {
button.backgroundColor = UIColor.blueColor()
button.setTitle("Button Title", forState: UIControlState.Normal)
}
Your UIButton #IBOutlet closePop is hooked up to a single #IBAction of the exact same name (closePop()). That closePop() IBAction ONLY dismisses the helpViewController - it doesn't do anything about the text or button color.
Your other #IBAction function like, in which you try to set the color & print "Is this even working?", is not hooked up to the button, and is never called.
i have an UIImagePickerController and 2 buttons. When I tap on button 1 I want to set the image of button 1. And when I tap on button 2 I want to set the image of button 2. I've successfully set the image of button 1 using UIImagePickerController but failed to do so with button 2. Here's my code:
var whichButton: Int = 0
func displayImagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func chooseImageOne(sender: AnyObject) {
displayImagePicker()
whichButton = 1
}
#IBAction func chooseImageTwo(sender: AnyObject) {
displayImagePicker()
whichButton = 2
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
if whichButton == 1 {
self.imageOne.setImage(image, forState: UIControlState.Normal)
} else if whichButton == 2 {
self.imageTwo.setImage(image, forState: UIControlState.Normal)
}
}
As you can see I tried having a var to keep track of which button I'm tapping on. I'm not sure what I've done in the didFinishPickingImage func is right. I'm very new to swift, if anyone can shed some light it will really be great! thanks in advance
I have personally checked your code on xcode and its correct. Please see if you have given IBOutlet to self.imageTwo button and also check for the IBAction i.e touchupInside for the imageTwo button. else everything is fine
Your code is functionally correct. Looks like your #IBAction functions are not hooked up correctly, or the #IBOutlet of the second button. You could easily check this with print statements in the button handlers, or in the debugger.
I want to add an image to a button, and when it is clicked, i want it to change. I'm very new to Swift so I know very little.
I have it like this:
//
// ViewController.swift
// Tip Calculator
//
// Created by ios4 on 10/16/15.
// Copyright (c) 2015 ios4. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var tipAmount: UILabel!
#IBOutlet weak var userBillTextField: UITextField!
#IBOutlet weak var tenOutlet: UIButton!
override func viewDidLoad()
{
tipAmount.text = " "
// var billDouble = (userBillTextField.text as NSString).doubleValue
super.viewDidLoad()
}
#IBAction func calculateButton(sender: UIButton)
{
var billDouble = NSString(string: userBillTextField.text).doubleValue
tipAmount.text = String( stringInterpolationSegment: billDouble * 0.15)
}
#IBAction func tenButton(sender: UIButton)
{
}
and I want the outlet called ten outlet to change to a different image called 10_selected_image from 10_unselected_image.
Any help?
Here are my instructions for this : https://s3.amazonaws.com/mmhighschool/MasterDocs/TipCalculator/TipCalculatorAppDirections.pdf
I'm currently working on stretch 3
You should be able to use set image for control state in your button action
button.setImage(image: UIImage(named: <image name>), forState: UIControlState.Normal)
If you need more info about how to make a "toggle button" this thread has a good answer to that
How to use a UIButton as a toggle switch
For me in Swift 5 is working like:
boton1.setBackgroundImage(UIImage(named: "image Name"), for: UIControl.State.normal)
My first question here. I'm making the jump from Delphi and Pascal to Xcode and Swift and feeling totally overwhelmed by the change.
I'm simply attempting to change the text of a label when a button is clicked. Here is my code from ViewController.swift
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var Label1: NSTextField!
#IBOutlet weak var ChangeText: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ButtonPressed(sender: AnyObject) {
Label1.stringValue = "Hello World"
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
When I run the application as soon as I click the button the application hangs.
I've also tried exchanging stringValue with text but NSTextField does not use this. I can't seem to make the label show up as UITextField.
What am I doing wrong?
Im simply trying to make it so when I click on a UIButton (for which it currently shows the image of a shell), the image changes into something else (in this case, a coin).
This is what i tried so far and have not had any success. I cant find anything to do this for Swift.Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lblOutput: UILabel!
#IBOutlet weak var lblWin: UILabel!
#IBOutlet weak var lblLost: UILabel!
#IBOutlet weak var lblWinsAmt: UILabel!
#IBOutlet weak var lblLossesAmt: UILabel!
let coin = UIImage(named: "penny_head") as UIImage;
override func viewDidLoad() {
super.viewDidLoad()
//imgShell1.hidden = true //doesnt work
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnStart(sender: UIButton) {
}
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
The way you're setting up the control is incorrect. Assuming you have a button property named btnShell (and it's the button you want to setup) change your viewDidLoad() method to:
override func viewDidLoad()
{
super.viewDidLoad()
btnShell.setImage(imgShell1, forState:.Normal);
btnShell.setImage(coin, forState:.Highlighted);
}
And then remove the setImage(_:forState:) call from the action method:
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
To permanently change the button image on tap, you have to use the .Normal enum case and not .Highlighted for the control state:
sender.setImage(coin,forState: UIControlState.Normal)
Setting the image for the .Highlighted state makes the new image appear only when the button is in that state, i.e. when it is tapped.
If you are looking to change the UIButton's background image permanently you have to use Antonio's method:
sender.setImage(coin,forState: UIControlState.Normal)
This won't change the UIKit's default highlighting when you tap the button. When you don't want the button to be highlighted when you touch it or have different appearances for different states, then you might be better off using an UIImageView.
In viewDidLoad():
imgView?.image = imgOne
imgView?.userInteractionEnabled = true
imgView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "changeImage:"))
The function that changes the image:
func changeImage(recognizer: UITapGestureRecognizer){
self.imgView?.image = imgTwo
}
You can also use isSelected.
button.setImage(image2, for: .normal)
button.setImage(image1, for: .selected)