I'm new to swift and I've searched different places and couldn't really find anything helpful.
I am in this case that I pick an image from UIImagePickerController when pressing on the button:
#IBAction func chooseImage(_ sender: Any){}
which works and I can access the photo library and choose an image but..
the thing is that I want to set it to the button image.
I save the image to:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// this works with an UIimageView.image but I can't get it to work with the button
???.image = image
I believe the way to do it is to say; button.ImageView.image = image and this can only be done by creating a variable called UIButton!??
and then I can set
button.ImageView.image = image
otherwise I can't enter the method ImageView.image
But the thing is that chooseImage is the same button I use for the action of receiving the image... So can I both make a #IBOutlet weak var button: UIButton! and #IBAction on the same button??
Well I tried and created both a
#IBOutlet weak var button: UIButton!
and
#IBAction func chooseImage(_ sender: Any) {
button.imageView.image = image
}
but nothing happened It might sound confusing,but there is two questions. Is it possible to do it this way? and if yes, why isn't the picture being shown when doing
button.imageView.image = image?
and if not please tell me what im doing wrong :-)
Thanks!
someButton.setImage(imagenew, for: .normal)
There is a setimage method for UIButton. you can also set image as background image. There is a method called setbackgroundImage.
try this
button.setImage(image, for: .normal) // Swift 3
Use setImage() method to set the foreground image of a button. However, if your buttons are all blue, that's because there is a feature for images called "Rendering Mode" you should be aware of, please refer to Template Images for more information:
button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
Related
I have 2 UIViews that I converted to UIColorWells.
#IBOutlet weak var colorWell1: UIColorWell!
#IBOutlet weak var ColorWell2: UIColorWell!
When I run the app, I see the color wells just fine (see image below). However, when I try to click on them, the actual color picker never opens. It seems like its just the image of the color well showing up.
Is there method I have to create to make them open, or is it built in? This is what I have pertaining to the colorWells below:
override func viewDidLoad() {
super.viewDidLoad()
colorWell1.addTarget(self, action: #selector(colorWellChanged(_:)), for: .valueChanged)
colorWell2.addTarget(self, action: #selector(colorWellChanged(_:)), for: .valueChanged)
}
#objc func colorWellChanged(_ sender: Any) {
colorWell1.backgroundColor = colorWell1.selectedColor
colorWell2.backgroundColor = team2ColorWell.selectedColor
}
This is what the colorWells look like: enter image description here
This is my folder structure:
enter image description here
I want the user to choose the preferred color by clicking the wanted button, and based on the choice it will be the background color of all pages in the App.
The code given is what I have used to change the background color through code, as shown in the image attached Screenshot of page sample . However, it changes temporary only and does not get saved when I move to another page and get back.
class ColorViewController: UIViewController {
#IBOutlet weak var redBtn: UIButton!
#IBOutlet weak var blueBtn: UIButton!
#IBAction func changeToRed(_ sender: UIButton) {
self.view.backgroundColor = UIColor.green
}
#IBAction func changeToBlue(_ sender: UIButton) {
self.view.backgroundColor = UIColor.cyan
}
If you also know how to save this color for a registered user (So every time the user signs in, the chosen background stays as is instead of reseting to default) it would be great. Please advise if you know the solution, I am new on Swift.
For saving user's color choice, you can use UserDefaults, that will allow you to store small sized information (like color preference) inside memory. So you can use something like this:
UserDefaults.standard.set(UIColor.red , forKey: "themePreferenceKey")
That will store Red choice in memory that'll be reachable with key themePreferenceKey later on.
For changing view/button background colors according to user's saved choice, you must fetch the value of themePreferenceKey whenever a view is Appeared, and change the colors accordingly. This can be implemented inside viewDidAppear method. Such as:
override func viewDidAppear(_ animated: Bool) {
if let preferredColor = UserDefaults.standard.object(forKey: "themePreferenceKey") as? UIColor {
self.view.backgroundColor = preferredColor
}
}
I'm making an extremely simple iOS app. I press a button and the image changes. The problem I'm running into is every time I press the button, it's like the button goes to the bottom of the phone simulator and lays on top of the button I originally pressed.
Also the image only stays for a split second before disappearing. (I'm assuming these actions go hand in hand).
Here is the code if anyone is able to help.
import UIKit
class ViewController: UIViewController {
#IBAction func generateHero(_ sender: UIButton) {
//list of Images in array
let image : NSArray = [ UIImage(named: "batman.jpg")!,
UIImage(named: "the-flash.jpg")!,
UIImage(named: "Deadpool.jpg")!,
UIImage(named: "green-arrow.jpg")!,
UIImage(named: "iron-man.jpg")!]
//random image generating method
let imagerange: UInt32 = UInt32(image.count)
let randomimage = Int(arc4random_uniform(imagerange))
let generatedimage: AnyObject = image.object(at: randomimage) as AnyObject
self.heroImage.image = generatedimage as? UIImage
}
#IBOutlet weak var heroImage: UIImageView!
}
You are doing a lot of unnecessary conversions in random image generation, if you have used Array instead of NSArray you could use .randomElement() function that returns random element of array. So you would just do
self.heroImage.image = image.randomElement()
I'm new to Swift and to stackoverflow so please comment for any improvements. I can make to my asking of questions!
I have created a UIButton that has an image. When tapped, the image is supposed to change to another image. Currently, once tapped, it 'flashes' with the image it is supposed to change to and then immediately changes back to the original image.
I created an outlet:
#IBOutlet var buttonImage: UIButton!
Then I added this:
override func viewDidLoad() {
super.viewDidLoad()
//Change image.
buttonImage.setImage(UIImage(named:"image1.png"),forState:UIControlState.Normal)
buttonImage.setImage(UIImage(named:"image2.png"),forState:UIControlState.Highlighted)
}
Help is gratefully received.
EDIT - added error screenshot.errorscreenshot
You need to change your viewDidLoad code like this
buttonImage.setImage(UIImage(named:"image1.png"),forState:UIControlState.Normal)
buttonImage.setImage(UIImage(named:"image2.png"),forState:UIControlState.Selected)
Now change you IBAction like this
#IBAction func btnTap(sender: UIButton) {
sender.selected = !sender.selected
}
Hope this will help you.
You need to assign two images for the button like the screenshots below.
As you can see I have state config as Default and Selected.
Later on the action of button you can do
#IBAction btnTapAction(sender: UIButton) {
if sender.selected{
sender.selected = false
}
else{
sender.selected = true
}
}
I am new to Swift programming and really have high hopes from all the experts out there. While creating a simple app I ran into memory issues and my app crashed. Below are more details about my app..
My app has an image view, three images and three buttons in toolbar. All my app does right now is changes image with button press. Example if you press say button1, it will load image1, if you press button2 it would load image 2 and if you press button 3 it would load image 3.
This app crash after 1 cycle, like I can tap all the three buttons and it would work, however if I tap on any button after that it would just crash.
I am testing this on iPad mini. Works perfectly fine on simulator. Any help would be greatly appreciated. I head somewhere that UIImage (named:) can be an issue, but I don't know how to replace that with anything else in Swift.
Here is the code for it
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var TestImage: UIImageView!
#IBAction func Button1(sender: AnyObject)
{
TestImage.image = UIImage (named: "Image1.jpg")
}
#IBAction func Button2(sender: AnyObject)
{
TestImage.image = UIImage (named: "Image2.jpg")
}
#IBAction func Button3(sender: AnyObject)
{
TestImage.image = UIImage (named: "Image1.jpg")
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The problem with UIImage(named: name) is that it caches the images. As the documentation says:
If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.
Thus, if you have memory problems arising from the size/number of images in the system cache, you can use UIImage(contentsOfFile: path) rather than UIImage(named: name):
if let path = NSBundle.mainBundle().pathForResource("Image1", ofType: "jpg") {
TestImage.image = UIImage(contentsOfFile:path)
}
I reduced the size using png 8 format in ps and it fixed the issue for me.. Thanks all for your help :-)