Can you change the background image each time you click the button? - ios

I've checked the documentation and have successfully added an image as a background, however, I can't change it now that it's been set.
What I want to do is to change the background Image each time I click the button. Looking online I've found information on how to change the buttons background, but not the actual background.
import UIKit
class ViewController: UIViewController {
var arrays = ["A", "b", "C", "D", "E", "F"]
var currentIndex = 0
var image = UIImage()
var image3 = UIImage()
#IBOutlet weak var ChangeText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ChangeText.text = arrays[currentIndex]
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "LaunchImage")!)
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image2")!)
}
#IBAction func Button() {
currentIndex += 1
if currentIndex == arrays.count {
currentIndex = 0
}
ChangeText.text = arrays[currentIndex]
if image == UIImage(named: "Image2") {
print("Image")
}
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image2")!)
}
}
Also is it OK to force unwrap UIImage I know force unwrapping is frowned upon however I know for sure that I will have a background image.
I tried this as well but Im having the same problem it wont change the background image more than once.
```
#IBAction func Button() {
currentIndex += 1
if currentIndex == arrays.count {
currentIndex = 0
}
ChangeText.text = arrays[currentIndex]
if image == UIImage(named: "Image2") {
print("Image")
}
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image2")!)
if image3 == UIImage(named: "Image3") {
print("Image")
}
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image3")!)
}
}
```

I'm not sure where the problem is, as you haven't shown us what you have already tried.
The same code that you have used to set the background view can be used anywhere, and as often as you like
if <some condition>
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "one")!)
}
if <another condition>
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "two")!)
}

I don't think your question is related to the buttons so much as general concepts, like conditions. As Russel answered, you simply need conditions. You've already demonstrated image loading is doable, so now you just need to do it "again" with a different image.
I have a few tips. First, don't name functions with nouns, say ButtonTapped or similar. Button, in swift 3, will be/is a UIButton, so it won't work as you expect anyway.
I realize you were not changing the Button's background, but I thought you were. If you were, Buttons don't behave like images and views. They have "Background for state" and "title for state". Heck, you can't even scale them using Core Animation, you have to scale their superview to see it. Although I'd hold off on Core Animation for now.
What you want to do is what Russel said, but try something simple. Like:
var switch:bool = true;
func buttonTapped() {
if (switch == true) {
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "one");
} else {
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "two");
}
switch = !switch;
}
I would first do something easy though to prove it's working
self.view.backgroundColor = UIColor.blackColor(); and orange/white anything.
Whether you should force unwrap things or not, gaining good naming habits, understanding structure, etc... I would recommend learning C++. A simple C++ tutorial will cover more structure and modularization than any beginner book on swift or iPhone programming. Plus, every other language is just a fraction of its features, so you'll pick everything else up super quick.

Replace your code with this:
#IBAction func Button() {
currentIndex += 1
if currentIndex == arrays.count {
currentIndex = 0
}
ChangeText.text = arrays[currentIndex]
if image == UIImage(named: "Image2")
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image3")!)
return;
}
else if image3 == UIImage(named: "Image3")
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image4")!)
return;
}
else if image == UIImage(named: "Image")
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image2")!)
return;
}
else
{
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Image")!)
return;
}
}

Related

Unable to change multiple button colours on user's tap swift iOS?

In my project I am using 6 buttons in one screen.I want to change the button color based on user's tap and "day order value". i am getting "day order value" from server.for example user day order value is equal to 1, day1 button background color should be red if user taps on day2 button day2 button should be in blue and remaining all button background colour should be white.
Please see the below screenshot.
if user pressed on one button that particular button should be highlight with some color remaining buttons should be same color. I can able to change button color by checking each condition but I want to write in simple manner.
see the following code which i have i tried for "dayoredrvalue".
func UpdateButtoncolor()
{
let dayOrderStr = UserDefaults.standard.string(forKey: "dayOrderStr")
print("dayOrderStr--",dayOrderStr)
if (dayOrderStr?.isEqual("1"))!{
self.day1Btn.backgroundColor = UIColor.red
self.day2Btn.backgroundColor = UIColor.white
self.day3Btn.backgroundColor = UIColor.white
self.day4Btn.backgroundColor = UIColor.white
self.day5Btn.backgroundColor = UIColor.white
self.day6Btn.backgroundColor = UIColor.white
}else if(dayOrderStr?.isEqual("2"))!
{
self.day1Btn.backgroundColor = UIColor.white
self.day2Btn.backgroundColor = UIColor.red
self.day3Btn.backgroundColor = UIColor.white
self.day4Btn.backgroundColor = UIColor.white
self.day5Btn.backgroundColor = UIColor.white
self.day6Btn.backgroundColor = UIColor.white
}else if(dayOrderStr?.isEqual("3"))!
{
self.day1Btn.backgroundColor = UIColor.white
self.day2Btn.backgroundColor = UIColor.white
self.day3Btn.backgroundColor = UIColor.red
self.day4Btn.backgroundColor = UIColor.white
self.day5Btn.backgroundColor = UIColor.white
self.day6Btn.backgroundColor = UIColor.white
}else if(dayOrderStr?.isEqual("4"))!
{
self.day1Btn.backgroundColor = UIColor.white
self.day2Btn.backgroundColor = UIColor.white
self.day3Btn.backgroundColor = UIColor.white
self.day4Btn.backgroundColor = UIColor.red
self.day5Btn.backgroundColor = UIColor.white
self.day6Btn.backgroundColor = UIColor.white
}else if(dayOrderStr?.isEqual("5"))!
{
self.day1Btn.backgroundColor = UIColor.white
self.day2Btn.backgroundColor = UIColor.white
self.day3Btn.backgroundColor = UIColor.white
self.day4Btn.backgroundColor = UIColor.white
self.day5Btn.backgroundColor = UIColor.red
self.day6Btn.backgroundColor = UIColor.white
}else
{
self.day1Btn.backgroundColor = UIColor.white
self.day2Btn.backgroundColor = UIColor.white
self.day3Btn.backgroundColor = UIColor.white
self.day4Btn.backgroundColor = UIColor.white
self.day5Btn.backgroundColor = UIColor.white
self.day6Btn.backgroundColor = UIColor.red
}
}
As per your query, It's quite simple. Just follow the following -
Step 1: Add an UIButton object in your viewController. Like that -
var selectedButton: UIButton? = nil
Step 2: Add same button Action for all your buttons -
#IBAction func btnActionSelection(_ sender:UIButton){
if(selectedButton == nil){ // No previous button was selected
updateButtonSelection(sender)
}else{ // User have already selected a button
if(selectedButton != sender){ // Not the same button
selectedButton?.backgroundColor = .clear
updateButtonSelection(sender)
}
}
}
Step 3: Now, Update button selection
func updateButtonSelection(_ sender: UIButton){
UserDefaults.standard.set("\(sender.tag)", forKey: "dayOrderStr")
selectedButton = sender
selectedButton?.backgroundColor = .green
}
Step 4: Check User selected day (For that you need to add tag on buttons from 1 to 6 respectively)
override func viewDidLoad() {
super.viewDidLoad()
// Check user's selected day
if let selectedDay = UserDefaults.standard.value(forKey: "dayOrderStr") as? String{
debugPrint("selectedDay: "selectedDay) // Get user's selected day
if let btn = self.view.viewWithTag(Int(selectedDay)!){
updateButtonSelection(btn)
}
}
//Other stuff
}
I have attached a demo for you using my logic:
For this you need to take a Group Outlets of your UIButton and assign a unique tag to each and then rest logic is described in the demo attached below.
like
#IBOutlet var btnAllSelected: [UIButton]!
And then simple logic like this:
#IBAction func btnAllClicked(_ sender: UIButton) {
for button in btnAllSelected {
if sender.tag == button.tag{
button.isSelected = true;
button.backgroundColor = UIColor.green
}else{
button.isSelected = false;
button.backgroundColor = UIColor.red
}
}
if sender.tag == 1{
print("Button 1 selected")
}else if sender.tag == 2{
print("Button 2 selected")
}else if sender.tag == 3{
print("Button 3 selected")
}else if sender.tag == 4{
print("Button 4 selected")
}else if sender.tag == 5{
print("Button 5 selected")
}else if sender.tag == 6{
print("Button 6 selected")
}
}
Link to the Demo
FYI:- Please ignore the pods installed in it. I edited some another demo and made a one for you.
Hope this helps.
You should create New Referencing Outlet Collections for all your UIButtons like this,
#IBOutlet var arrButtons: [UIButton]!
Implement only one Button tap events for all your buttons, Please find belo code.
#IBAction func btnClicked(_ sender: UIButton) {
arrButtons.forEach({$0.backgroundColor = UIColor.red})
sender.backgroundColor = UIColor.darkGray
}
Simplified code, it uses an array of the buttons and an index:
let buttonArray = [day1Btn, day2Btn, day3Btn, day4Btn, day5Btn, day6Btn]
buttonArray.forEach { $0.backgroundColor = .white }
guard let dayOrderStr = UserDefaults.standard.string(forKey: "dayOrderStr"),
let dayOrderIndex = Int(dayOrderStr), 1...buttonArray.count ~= dayOrderIndex {
buttonArray[dayOrderIndex-1].backgroundColor = .red
}
It can be still simpler if you save the value in UserDefaults as Int
Here is one solution among many others.
#IBOutlet var buttons: [UIButton]! // link all the buttons from the storyboard
func changeColorButton(sender: UIButton) {
// default appearance for all buttons
for button in buttons {
button.backgroundColor = UIColor.green
}
// update color only for the button clicked
sender.backgroundColor = .orange
}
#IBAction func buttonTapped(_ sender: UIButton) {
updateFocusPicture(sender: sender)
}

Swift - changing image view background image via segmented control

The title itself explains as much as i will be able to. Basically, i have a segmented control that i want to change the image within my image view after each segment is selected, but i can't seem to apply or find the logic to resolve my problem. The answer itself is probably very simple, but i'm really new to Swift and didn't manage to find an answer anywhere, so i would love a solution to my problem. Thanks!
#IBOutlet weak var newImageView: UIImageView!
#IBAction func chooseImage(sender: AnyObject) {
if myPhotoSegment.selectedSegmentIndex == 0
{
newImageView = UIImage(named: "3.jpg")
}
if myPhotoSegment.selectedSegmentIndex == 1
{
}
You can't set the value of a UIImageView to a UIImage.
Set the value of newImageView.image instead. This is also a good opportunity for a switch statement.
#IBAction func chooseImage(sender: AnyObject) {
switch myPhotoSegment.selectedSegmentIndex {
case 0:
newImageView.image = UIImage(named: "3.jpg")
case 1:
newImageView.image = UIImage(named: "4.jpg")
default:
newImageView.image = nil
}
}
Segment using image in imageview in swift4
#IBOutlet weak var bgimage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.red
let itemsimg = ["google", "facebook", "instagram" , "twitter"]
let customSI = UISegmentedControl(items: itemsimg)
customSI.selectedSegmentIndex = 0
customSI.frame = CGRect(x:50, y:100, width:300, height: 40)
customSI.layer.cornerRadius = 5.0
customSI.backgroundColor = UIColor.black
customSI.tintColor = UIColor.white
customSI.addTarget(self, action: #selector(changeimg),for: .valueChanged)
self.view.addSubview(customSI)
}
#objc func changeimg(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 1:
bgimage.image = UIImage(named: "facebook")
case 2:
bgimage.image = UIImage(named: "instagram")
case 3:
bgimage.image = UIImage(named: "twitter")
default:
bgimage.image = UIImage(named: "google")
}
}
}

change page Indicator Image [SMPageControl] / EAIntroView in swift

I'm trying to change the indicator image , following the example in EAIntroView
here is the objective-c code from EAIntroView
SMPageControl *pageControl = [[SMPageControl alloc] init];
pageControl.pageIndicatorImage = [UIImage imageNamed:#"pageDot"];
pageControl.currentPageIndicatorImage = [UIImage imageNamed:#"selectedPageDot"];
[pageControl sizeToFit];
intro.pageControl = (UIPageControl *)pageControl;
intro.pageControlY = 130.f;
and here is the swift code I'm trying to implement
// SMPageControl
pageControl = SMPageControl()
pageControl.pageIndicatorImage = UIImage(named: "pageDot")
pageControl.currentPageIndicatorImage = UIImage(named: "selectedPageDot")
pageControl.sizeToFit()
pageControl.backgroundColor = UIColor.clearColor()
intro.pageControl = pageControl as? UIPageControl
swift code has a warning here
intro.pageControl = pageControl as? UIPageControl
the warning is :
Cast from 'SMPageControl!' to unrelated type 'UIPageControl' always fails
any help ?
For changing page Indicator Image [SMPageControl] / EAIntroView in swift I have created custom class of UIPageControl like below:
import UIKit
class CustomPageControl: UIPageControl {
let activePage: UIImage = UIImage(named: "icon-selected-dot")!
let inActivePage: UIImage = UIImage(named: "icon-dot")!
override var numberOfPages: Int {
didSet {
updateDots()
}
}
override var currentPage: Int {
didSet {
updateDots()
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.pageIndicatorTintColor = UIColor.clear
self.currentPageIndicatorTintColor = UIColor.clear
self.clipsToBounds = false
}
func updateDots() {
var i = 0
for view in self.subviews {
var imageView = self.imageView(forSubview: view)
if imageView == nil {
if i == self.currentPage {
imageView = UIImageView(image: activePage)
} else {
imageView = UIImageView(image: inActivePage)
}
imageView!.center = view.center
view.addSubview(imageView!)
view.clipsToBounds = false
}
if i == self.currentPage {
imageView!.alpha = 1.0
imageView?.image = activePage
} else {
imageView!.alpha = 0.5
imageView?.image = inActivePage
}
i += 1
}
}
fileprivate func imageView(forSubview view: UIView) -> UIImageView? {
var dot: UIImageView?
if let dotImageView = view as? UIImageView {
dot = dotImageView
} else {
for foundView in view.subviews {
if let imageView = foundView as? UIImageView {
dot = imageView
break
}
}
}
return dot
}
}
then in your class just add these lines and you can use custom images for dot
//Custom page Control
let pageControl = CustomPageControl()
pageControl.updateDots()
intro.pageControl = pageControl
Hope it will work for you! #ynamao
You can see from the source code of SMPageControl that it isn't a subclass of UIPageControl. Which means the error is expected: UIPageControl is a completely unrelated type, to which the value cannot be cast.
The Objective-C you pointed to might work, but it's bad and wrong: inline cast to UIPageControl achieves nothing here and can cause internal inconsistencies.
This is exactly the kind of sloppiness that Swift compiler is designed to prevent, and it's doing its job well.
Your best bet is to forgo using this library in Swift code.

Load imageView from Xcassets using Switch statement

I have the images for #1 #2 and #3 in the Xcassets and am trying to load the image onto a scrollview page using the code below that switches the image due to the age its on. The page is determined by the position and the switch statement is called in the viewWillLoad function. The images are not loading but sounds are working so I know the it is the image loading that is the problem. Can you help?
override func viewDidDisappear(animated: Bool) {
self.imageView.removeFromSuperview()
self.imageView.image = nil
}
override func viewWillAppear(animated: Bool) {
showImageView()
let tapGestureImage = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
imageView.addGestureRecognizer(tapGestureImage)
imageView.userInteractionEnabled = true
}
// MARK: BWWalkthroughPage Implementation
func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
// getting the page number from the scroll position. First page loads as nil so want it to be zero.
screenPage = Int(((position / view.bounds.size.width) + 1) - 1)
}
func showImageView() {
// change imageView in bundle depending on which scrollview page you are.
switch screenPage {
case 0:
self.imageView.image = UIImage(named: "Aligator", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
self.view.addSubview(imageView)
case 1:
self.imageView.image = UIImage(named: "Bear", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
self.view.addSubview(imageView)
default:
self.imageView.image = nil
}
}
A few things are important for you to understand.
You do not need to add/remove the image view from the view hierarchy over and over. Simply calling imageView.image = nil will suffice.
The second thing is that you don't need to use the full method UIImage(named:inBundle:compatibleWithTraitCollection:). You should be able to simply use UIImage(named:). If you find yourself having to use the former, you may be taking bigger bites than you can handle at this stage in your career.
The third thing is that when you override a method, you must call super in 99% of the cases.
Here's an example that should work:
import UIKit
class MyViewController: UIViewController {
override fun viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.userInteractionEnabled = true
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated: animated)
self.imageView.image = nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated: animated)
showImageView()
}
func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
screenPage = Int(((position / view.bounds.size.width) + 1) - 1)
}
func showImageView() {
switch screenPage {
case 0:
imageView.image = UIImage(named: "Aligator")
case 1:
imageView.image = UIImage(named: "Bear")
default:
imageView.image = nil
}
}
}

Stretch Background for View in Swift

I am using adding Background in iOS Swift App using:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
However, it does not cover the Screen till bottom. I searched Other questions:
var backImage = UIImage(named: "background")
var resizablebackImage = backImage?.resizableImageWithCapInsets(UIEdgeInsets(top:10,left:0,bottom:10,right:0))
self.view.backgroundColor = UIColor(patternImage:resizablebackImage!)
That does not work. Any ideas?
If your intention is to set it as the background image, don't make image as pattern color and fill it as background color. Instead create an UIImageView set your image as it's image and add it to your UIView.
var bgImage = UIImage(named: "background");
var imageView = UIImageView(frame: self.view.bounds);
imageView.image = bgImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
For Swift 1.x & Swift 2 plus Device Rotation Detection
Please see my code below. Just set bgImageName to the name of your image and call setBackgroundImage(). I added an auto-reload in case of a device rotation.
var bgImage = UIImage()
var bgImageView = UIImageView()
var bgImageName = ""
override func viewDidLoad() {
super.viewDidLoad()
bgImageName = "bg-orange" // or whatever your image is called
setBackgroundImage()
}
func setBackgroundImage() {
if bgImageName > "" {
bgImageView.removeFromSuperview()
bgImage = UIImage(named: bgImageName)!
bgImageView = UIImageView(frame: self.view.bounds)
bgImageView.image = bgImage
self.view.addSubview(bgImageView)
self.view.sendSubviewToBack(bgImageView)
}
}
// detect device orientation changes
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("rotated device to landscape")
setBackgroundImage()
} else {
print("rotated device to portrait")
setBackgroundImage()
}
}

Resources