Change background image with button click - ios

I can change background image on viewDidLoad func like this:
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
i would like to do same action with button click like this:
#IBAction func flip4btn5(_ sender: Any)
{
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
but it does not change background image. Why ? What do you think ?
I'm using Swift 4.1.

Don't create a new image. just change the picture of the first UIImage in your button action like this:
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")

Try this code, It's working fine.
class ViewController: UIViewController {
var myBackgroundImage = UIImageView (frame: UIScreen.main.bounds);
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
#IBAction func flip4btn5(_ sender: UIButton) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}

Don't keep adding UIImageViews everytime you want to change the background image.
Place a UIImageView in the view hierarchy where it is needed and keep a reference to it. Then set the image property on it as needed.
class ViewController: UIViewController {
#IBOutlet weak var backgroundImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
}
#IBAction func flip4btn5(_ sender: Any) {
backgroundImageView.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}
You can set the contentMode either in the storyboard or in viewDidLoad. You don't need to keep setting it after updating an image.

let myBackgroundImage = UIImageView (frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(myBackgroundImage)
}
#IBAction func ButtonPressed(_ sender: Any) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}

Related

Add constraints to a UIViewController does not work

Simple question, but I don't get the answer of satisfaction.
So, I want to add some constraints to my added UIViewController via code.
Thank you so much :)
override func viewDidLoad() {
let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
let imageLogoView = UIImageView(image: imageLogo!)
setImageContraints()
}
func setImageContraints(){
imageLogoView.translatesAutoresizingMaskIntoConstraints = false
imageLogoView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageLogoView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
In the func setImageContraints:
Error: Use of unresolved identifier 'imageLogoView'
You are using variable imageLogoView outside of it's visibility/life cycle scope. You should have an instance variable instead:
class SomeViewController {
var imageLogoView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad() // <-- notice this
let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
self.imageLogoView = UIImageView(image: imageLogo!)
setImageContraints()
}
}
or simpler:
class SomeViewController {
let imageLogoView = UIImageView(image: UIImage(imageLiteralResourceName: "pictureIsInAssets"))
override func viewDidLoad() {
super.viewDidLoad() // <-- notice this
setImageContraints()
}
}
And don't forget to add the image view to the view.
imageLogoView is no global variable.
You have to declare it like that:
class ViewController: UIViewController{
let imageLogoView: UIImageView!
override func viewDidLoad() {
let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
imageLogoView = UIImageView(image: imageLogo!)
setImageContraints()
}
}

Passing image from ViewController to ViewController

I try to pass an image from one ViewController1 to another ViewController2 when a button is tapped. I am using segues in my Storyboard.
ViewController1
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imagePicker: UIImagePickerController!
#IBAction func editPhoto(_ sender: UIButton) {
let editViewController = storyboard?.instantiateViewController(withIdentifier: "EditImageViewController") as! EditImageViewController
editViewController.imageForEdit = imageView.image!
print(imageView)
print(imageView.image!)
navigationController?.pushViewController(editViewController, animated: true)
}
#IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
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.
}
}
print(imageView) results in
some(UIImageView: 0x7fc34df0e630; frame = (8 29; 303 443); clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = CALayer: 0x60000023e520)
and print(imageView.image!) in
size {3000, 2002} orientation 0 scale 1.000000
ViewController2
import UIKit
class EditImageViewController: UIViewController {
var imageForEdit = UIImage()
#IBOutlet weak var editingImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
editingImage.image = imageForEdit
print(imageForEdit)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
print(imageForEdit) results in
size {0, 0} orientation 0 scale 1.000000
Why is that? Why isnt the image passed to ViewController2?
It seems to me that this could be a lot simpler. If you're using a Storyboard with a segue, you can easily accomplish this in prepare(for segue: UIStoryboardSegue, sender: Any?). Here's a sample storyboard:
In this case, ViewController has a segue on the Edit Image button to the EditImageViewController.
When you push that button, you get your prepare(for segue: call. Here's a sample ViewController:
class ViewController: UIViewController {
var imagePath = Bundle.main.path(forResource: "icon8", ofType: "png")
var anEditableImage:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
if let imagePath = imagePath {
anEditableImage = UIImage(contentsOfFile: imagePath)
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? EditImageViewController {
destination.imageForEdit = anEditableImage
}
}
}
And here's the EditImageViewController:
class EditImageViewController: UIViewController {
var imageForEdit:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
print(imageForEdit ?? "Image was nil")
}
}
Using prepare(for segue: UIStoryboardSegue, sender: Any?) is the preferred way for a Storyboard-based app to pass data between View Controllers. It's very simple and it works.
Sample project is here if you want to see the working code:
https://www.dropbox.com/s/eog01bmha67c5mv/PushImage.zip?dl=0
var imageForEdit: UIImage? {
didSet {
editingImage.image = imageForEdit
}
}
Replace var imageForEdit = UIImage() with var imageForEdit : UIImage?
i test code my self , make sure that imageView have image
#IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
You can create an public variable so you can pase data from one viewcontroller to another view controller.
class variables
{
static var image = UIImage()
}
the 2 controller:
#IBOutlet weak var anotherviewcontroller: UIImageView!
anotherviewcontroller.image = variables.image

IOS Swift3 how to Remove Custom UIView randomly

I am building an iOS Application in swift 3, where I am creating dynamic UIViews. I need to remove custom view randomly. Please help me I am stuck with this for a long time. Thanks In Advance
class ViewController: UIViewController {
var myView: subView!
var y : CGFloat!
#IBOutlet weak var addButton: UIButton!
override func viewDidLoad() {
y = 1
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func cancelbutton(_ sender: UIButton) {
myView.removeFromSuperview()
}
#IBAction func buttonAction(_ sender: Any) {
y = y + 110
myView = subView(frame: CGRect(x: 80, y: y, width: 300, height: 100))
myView.backgroundColor = UIColor.green
myView.actionButton.addTarget(self, action: (#selector(cancelbutton(_:))), for: UIControlEvents.touchUpInside)
self.view.addSubview(myView)
}
}
As you can see in the above image when i click on Close the SubView(custome View) closes, but where as MyView with green color does not go and stays there. Someone please Help.........
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("subView",owner: self, options:nil)
self.addSubview(self.views)
Bundle.main.loadNibNamed("subView",owner: self, options:nil)
self.addSubview(self.views)
}
override init(frame: CGRect)
{
super.init(frame: frame)
Bundle.main.loadNibNamed("subView", owner: self, options: nil)
views.frame = bounds
self.addSubview(self.views)
}
#IBAction func buttonAction(_ sender: Any) {
views.removeFromSuperview()
}
The thing you are doing wrong is that you add multiple views of subView that why you selected does not remove. Please modify your code like given below.
The thing I have done is that whenever you will add new subView you will also set its tag value and when you select view to remove its tag value and place an if statement on that tag value.
class ViewController: UIViewController {
var myView: subView!
var y : CGFloat!
var tag : Int = 0
#IBOutlet weak var addButton: UIButton!
override func viewDidLoad() {
y = 1
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func cancelbutton(_ sender: UIButton)
{
let selectViewTagValue : Int = sender.tag /// save the selected view tag value
for object in self.view.subviews {
if ((object is subView) && object.tag == selectViewTagValue)
{
object.removeFromSuperview()
}
}
}
#IBAction func buttonAction(_ sender: Any) {
y = y + 110
myView = subView(frame: CGRect(x: 80, y: y, width: 300, height: 100))
myView.tag = tag
myView.actionButton.tag = tag
tag = tag + 1
myView.backgroundColor = UIColor.green
myView.actionButton.addTarget(self, action: (#selector(cancelbutton(_:))), for: UIControlEvents.touchUpInside)
self.view.addSubview(myView)
}
Try to change cancel action like this:
func cancelbutton(_ sender: UIButton)
{
if let myView = sender.superview {
myView.removeFromSuperview()
}
}
Just remove the button's container view, not the global myView.
I managed to fixed the delete issue, but currently I am unable to relocate the positions the customs views, as shows in the picture below, Kindly help me with this.

Adding UIView back to View

I have multiple subviews in my main view controller, I am using a delete button to remove one subview at a time. I am trying to allow the user to bring back the view that was deleted, but the view is not coming back. Any thoughts? In Swift.
#IBOutlet var tornView: UIView!
var deleted = 1
// Delete Button
#IBAction func deleteViewButton(sender: AnyObject) {
if deleted == 1 {
tornView.removeFromSuperview()
deleted = 2
}
}
// Brings View to Screen
#IBAction func showTornAnnotation(sender: AnyObject) {
if toggleState == 1 {
firstSlider.hidden = false
tornView.hidden = false
toggleState = 2
if deleted == 2 {
view.addSubview(tornView)
}
}
else {
firstSlider.hidden = true
tornView.hidden = true
toggleState = 1
}
}
If you want IBOutlet to be removed from the superView and get it added back then you should always use strong references to your IBOutlet. Being said you should also keep the position of the removed view so that you can use it when you are ready to add it back.
Edit: Sample code
#IBOutlet var customView: UIView!
var customViewFrame: CGRect?
override func viewDidLoad() {
super.viewDidLoad()
customView.backgroundColor = UIColor.blueColor()
}
#IBAction func remove(sender: AnyObject) {
customViewFrame = customView.frame
customView.removeFromSuperview()
}
#IBAction func add(sender: AnyObject) {
if let rect = customViewFrame {
customView = UIView.init(frame: rect)
customView.backgroundColor = UIColor.blueColor()
view.addSubview(customView)
view.bringSubviewToFront(customView)
}
}

how to change uiimage's image on button click in swift?

I'm trying change an uiimage control's containing image by clicking a button in swift. For this, i wrote a simple a "guess how many fingers i'm holding up" app. I've read some stackoverflow articles but couldn't solve the problem. Below you can see my code and my ui. How can i change change image on click?
Here's my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var inputField: UITextField!
#IBAction func clickedGuessButtonAction(sender: AnyObject) {
println("Guess button clicked")
var randomX = Int(arc4random()%6)
println("randomX = \(randomX)")
var guess = inputField.text.toInt();
let image0 = UIImage(named: "images/qm.jpg")
let image1 = UIImage(named: "images/tick.jpg")
let image2 = UIImage(named: "images/cross.jpg")
if((inputField.text) != nil){
if(guess == randomX){
println("correct")
myImageView.image=UIImage(named: "tick.jpg") // THIS IS NOT WORKING
myImageView.image=image1 // THIS IS NOT WORKING TOO
inputField.resignFirstResponder();// hides keyboard
}
else
{
println("wrong")
myImageView.image=UIImage(named: "cross.jpg")
inputField.resignFirstResponder();//hides keyboard
}
}
else{
println("invalid input. requires integer only")
inputField.resignFirstResponder();// hides keyboard
}
}
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.
}
}
And here's my UI:
You don't need to specify either the asset catalog's name or the image file's extension. Try removing those. For example,
myImageView.image = UIImage(named: "tick")
It may depend on the version of Xcode you are using. For me the following worked:
ImageView.image = UIImage(named: "Elephants.jpg")
In Swift:
myImageView = "nameOfImage";

Resources