Swift - changing image view background image via segmented control - ios

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")
}
}
}

Related

TabBar tappedIcon unTappedIcon Issue

When i tapped on my TabBar's first image it should be highlighted like the below image -
enter image description here
But when i tap on the first icon it's doing nothing, tap on the second icon it's highlighting the first icon, tap on the 3rd icon highlighting it's previous icon (second icon) and so on. It might be an indexing problem. Need some help to find this issue. Thank you. My TabBar current view-
enter image description here
Here is my code -
import UIKit
class ViewController: BaseViewController {
//MARK: Outlets
#IBOutlet var warningsIcon: UIImageView!
#IBOutlet var incidentsIcon: UIImageView!
#IBOutlet var notificationsIcon: UIImageView!
#IBOutlet var myMessagesIcon: UIImageView!
#IBOutlet var warningsTitle: UILabel!
#IBOutlet var incidentsTitle: UILabel!
#IBOutlet var notificationsTitle: UILabel!
#IBOutlet var myMessagesTitle: UILabel!
#IBOutlet var containerView: UIView!
//MARK: PROPERTIES
var previousSelectedIcon:UIImageView!
var previousSeelctedTitle:UILabel!
var previousIndex:Int!
var currentIndex:Int!
var previousVc:UIViewController!
fileprivate var i = 0
open var subViewController:UIViewController?
var unTappedIcon = ["warnings","incidents","notifications","my-messages"]
var tappedIcon = ["warnings_tapped","Incidents_tapped","notifications_tapped","myMessages_tapped"]
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
// Do any additional setup after loading the view, typically from a nib.
previousVc = self;
previousSelectedIcon = warningsIcon
previousSeelctedTitle = warningsTitle
previousIndex = 0;
currentIndex = 0;
//place sub view controller if any
placeSubViewControllerIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//place sub view controller if needed
func placeSubViewControllerIfNeeded() -> Void{
if let vc = subViewController {
vc.view.frame = self.containerView.frame
self.addChildViewController(vc)
//vc.view.frame = self.view.frame
self.containerView.addSubview(vc.view)
self.view.sendSubview(toBack: vc.view)
}
}
//MARK: For Tab bar
func updateTapView(title:UILabel, icon:UIImageView) {
previousSeelctedTitle.textColor = UIColor(red:0.60, green:0.60, blue:0.60, alpha:1.0)
previousSelectedIcon.image = UIImage.init(named: unTappedIcon[previousIndex])
title.textColor = UIColor(red:0.26, green:0.18, blue:0.49, alpha:1.0)
icon.image = UIImage.init(named: tappedIcon[currentIndex])
}
func removePreviousViewController() {
previousVc.willMove(toParentViewController: nil)
previousVc.view.removeFromSuperview()
previousVc.removeFromParentViewController()
}
func getStoryBoardByIndentifier(identifier:String)->UIStoryboard {
return UIStoryboard.init(name: identifier, bundle: nil)
}
func showSubViewContrller(subViewController:UIViewController) {
self.addChildViewController(subViewController)
subViewController.view.frame = containerView.frame
self.containerView.addSubview(subViewController.view)
subViewController.didMove(toParentViewController: self)
previousVc = subViewController
}
//Mark:- Action button for warnings
#IBAction func onClickWarnings(_ sender: UITapGestureRecognizer) {
print("Hi there i am just a warning")
self.warningsIcon.image = UIImage.init(named: "warnings_tapped")
previousIndex = currentIndex
currentIndex = 0
updateTapView( title: warningsTitle, icon: warningsIcon)
previousSeelctedTitle = warningsTitle
previousSelectedIcon = warningsIcon
if i > 0{
removePreviousViewController()
print("i am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "warnings")
let vc = storyBoard.instantiateViewController(withIdentifier: "WarningsViewController") as! WarningsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickIncidents(_ sender: UITapGestureRecognizer) {
print("Hi there i am just a warning")
self.incidentsIcon.image = UIImage.init(named: "Incidents_tapped")
previousIndex = currentIndex
currentIndex = 1
updateTapView( title: incidentsTitle, icon: incidentsIcon)
previousSeelctedTitle = incidentsTitle
previousSelectedIcon = incidentsIcon
if i > 0{
removePreviousViewController()
print("i am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "incidents")
let vc = storyBoard.instantiateViewController(withIdentifier: "IncidentsViewController") as! IncidentsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickNotifications(_ sender: UITapGestureRecognizer) {
print("Really true")
self.notificationsIcon.image = UIImage.init(named: "notifications_tapped")
previousIndex = currentIndex
currentIndex = 2
updateTapView(title: notificationsTitle, icon: notificationsIcon)
previousSeelctedTitle = notificationsTitle
previousSelectedIcon = notificationsIcon
if i > 0 {
removePreviousViewController()
print("I am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "notifications")
let vc = storyBoard.instantiateViewController(withIdentifier: "NotificationsViewController") as! NotificationsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickMyMessages(_ sender: UITapGestureRecognizer) {
print("ha ha..i believe in that")
self.myMessagesIcon.image = UIImage.init(named: "myMessages_tapped")
previousIndex = currentIndex
currentIndex = 3
updateTapView(title: myMessagesTitle , icon: myMessagesIcon)
previousSeelctedTitle = myMessagesTitle
previousSelectedIcon = myMessagesIcon
if i > 0 {
removePreviousViewController()
print("i am alreday removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "myMessages")
let vc = storyBoard.instantiateViewController(withIdentifier: "MyMessagesViewController") as! MyMessagesViewController
showSubViewContrller(subViewController: vc)
i += 1
}
}
Looks like you are adding view ineach viewcotroller which you want to show as if a tab bar item.. this might not be the right way to do.. what you can do is make your custom tabbar controller
class SampleViewController: UITabBarController {
#IBOutlet var tabBarView: UIView!
#IBOutlet weak var item1Btn: UIButton!
#IBOutlet weak var item2Btn: UIButton!
#IBOutlet weak var item3Btn: UIButton!
#IBOutlet weak var item4Btn: UIButton!
#IBOutlet weak var item5Btn: UIButton!
let item1Image = #imageLiteral(resourceName: "profileUnselected")
let item1Selected = #imageLiteral(resourceName: "profile")
let item2Image = #imageLiteral(resourceName: "notificationUnselected")
let item2Selected = #imageLiteral(resourceName: "notificationSelected")
let item3Image = #imageLiteral(resourceName: "game")
let item3Selected = #imageLiteral(resourceName: "game")
let item4Image = #imageLiteral(resourceName: "cookbooksUnselected")
let item4Selected = #imageLiteral(resourceName: "cookbooks")
let item5Image = #imageLiteral(resourceName: "searchTabUnselected")
let item5Selected = #imageLiteral(resourceName: "searchTabSelected")
let unSelectedColor = UIColor.lightGray
let selectedColor = UIColor.white
let appColor = UIColor(red: 22.0/255.0, green: 168.0/255.0, blue: 225.0/255.0, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 2436:
offsetHeight = 44.0
default:
print("unknown")
}
}
addTabView()
}
func addTabView() {
Bundle.main.loadNibNamed("TabBarView", owner: self, options: nil)
tabBarView.frame = CGRect(x:
0 , y: Helper.getScreenHeight() - AppConstants.kTabBarheight - offsetHeight, width: Helper.getScreenWidth(), height: AppConstants.kTabBarheight)
self.view.addSubview(tabBarView)
self.item3Btn.sendActions(for: .touchUpInside) //here i showed my third tab bar item initially
}
#IBAction func tabBarBtnClick(_ sender: UIButton) {
var isViewToChange = false
let currentIndex = self.selectedIndex
var tochangeIndex = sender.tag
self.item1Btn.setImage(item1Image, for: .normal)
self.item2Btn.setImage(item2Image, for: .normal)
self.item3Btn.setImage(item3Image, for: .normal)
self.item4Btn.setImage(item4Image, for: .normal)
self.item5Btn.setImage(item5Image, for: .normal)
switch sender.tag {
case 0:
self.item1Btn.setImage(item1Selected, for: .normal)
if currentIndex != 0{
isViewToChange = true
tochangeIndex = 0
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 1:
self.item2Btn.setImage(item2Selected, for: .normal)
if currentIndex != 1{
isViewToChange = true
tochangeIndex = 1
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 2:
if currentIndex != 2{
isViewToChange = true
tochangeIndex = 2
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 3:
self.item4Btn.setImage(item4Selected, for: .normal)
if currentIndex != 3{
isViewToChange = true
tochangeIndex = 3
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 4:
self.item5Btn.setImage(item5Selected, for: .normal)
if currentIndex != 4{
isViewToChange = true
tochangeIndex = 4
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
default:
break
}
if isViewToChange {
let _ = self.selectedViewController?.view
let _ = self.viewControllers?[tochangeIndex].view
self.selectedIndex = tochangeIndex
}
}
func hideTabbar() {
self.tabBar.isHidden = true
var frame = tabBarView.frame
frame.origin.y = Helper.getScreenHeight() + 200
tabBarView.frame = frame
}
func showTabbar() {
self.tabBar.isHidden = false
var frame = tabBarView.frame
frame.origin.y = Helper.getScreenHeight() - AppConstants.kTabBarheight - offsetHeight
tabBarView.frame = frame
}
}
here i have aded methods for you to either show the tab bar of hide as we push into the stack of each tab bar item..
Here added few images for your understanding
and also dont forgot to set the tag for each button in tab bar view, so that when any button clicked, same method is called and we handle it from there

UISegmentedControl if statement

I am trying learning the UISegmentedControl and want to figure out how to get it to work within an if statement to return one value based on selection and another value based on the other selection. There is only two values the UISegment can return - "Fixed" or "Varibale". The code below does not work but gives an idea what I want. The two variables are predefined.
#IBAction func calPenalty(_ sender: UIButton) {
let startDate = termStartDate.text
let mortgageTerm = Double(mortgageTermLabel.text!)
let discount = Double(mortgageDiscountLabel.text!)
let mtgCashback = Double(casbackRecieved.text!)
let mtgBalance = Double(mortgageBalance.text!)
let rate = Double(currentRate.text!)
//let mortgageType = mortgageType
let lender = Global.selectedRate
if let oneYear = Double((lender?.oneYear)!),
let twoYear = Double((lender?.twoYear)!),
let threeYear = Double((lender?.threeYear)!),
let fourYear = Double((lender?.fourYear)!),
let fiveYear = Double((lender?.fiveYear)!) {
let maturityDate = (getMaturityDate(startdate: startDate!, termMonths: Int(mortgageTerm!)))
let monthsToMaturity = daysBetweenDates(endDate: maturityDate)/365*12
let comparisonTerm = (IRDComparisonTerm(monthsToMaturity: monthsToMaturity))
let cashback = cashbackRepayment(cashbackRecieved: mtgCashback!, mtgTerm: Double(mortgageTerm!), mthsToMaturity: Double(monthsToMaturity))
print(cashback)
var comparisonRate: Double = 0
switch comparisonTerm
{
case 12:
comparisonRate = oneYear
case 24:
comparisonRate = twoYear
case 36:
comparisonRate = threeYear
case 48:
comparisonRate = fourYear
case 60:
comparisonRate = fiveYear
default:
comparisonRate = 0
} // end switch statement
print(comparisonRate)
let IRD = IRDPenalty(IRDComparisonRate: comparisonRate, mtgBalance: mtgBalance!, mthsToMaturity: Double(monthsToMaturity), discount: discount!, currentRate: rate!)
let threeMthsInterestPenalty = threeMonthsInterestPenalty(mtgBalance: mtgBalance!, mtgRate: rate!)
print (IRD)
print (threeMthsInterestPenalty)
var penalty: Double = 0
// var totalPenalty: Double = 0
if IRD > threeMthsInterestPenalty {
penalty = IRD + cashback
}else{
penalty = threeMthsInterestPenalty + cashback
}
// totalPenalty = penalty + cashback
calculationLabel.text = String(penalty)
}
}
// triggers result based on value selected
#IBAction func valueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
calculationLabel.text = String(penalty)
case 1:
calculationLabel.text = String(threeMthsInterestPenalty + cashback)
default:
calculationLabel.text = String(penalty)
}
}
Edit: I am still working on this problem. I have updated to the above code to show all the code within the IBAction. The #IBAction does not work as the variables are undefined based on where they are posted within the code. The Storyboard has a UIsegmentedControl with to values "Fixed and Variable. If the user selects fixed then I want it to show as per the IBAction for UISegement Control.
If what you want is to check when the value of your segmented control changes, and you want to do it programmatically, you firstly need to register a target-action method using valueChanged constant. Then, write up your valueChanged function. Check this out for more information.
import UIKit
class ViewController: UIViewController {
// Reference from Storyboard or Interface Builder
#IBOutlet weak var mortgageType: UISegmentedControl!
// For set up a UISegmentedControl programmatically
var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
// Programmatically setup
let items = ["Cinnamon", "Clove"]
segmentedControl = UISegmentedControl(items: items)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.frame = CGRect(x: 120, y: 200, width: 200, height: 30)
segmentedControl.tintColor = UIColor.black
segmentedControl.addTarget(self, action: #selector(self.valueChanged(_:)), for: .valueChanged)
self.view.addSubview(segmentedControl)
}
#IBAction func valueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("Hi")
case 1:
print("Bye")
default:
print("Nothing")
}
}
}
If you reference your UISegmentedControl from Storyboard and Interface Builder. You should also add an action to it.
Update to the edited question
#IBAction func calPenalty(_ sender: UIButton) {
if mortgageType.selectedSegmentIndex == 0 {
print("Fixed")
} else {
print("Variable")
}
}

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

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;
}
}

UIBarButtonItem changing image for Play/Pause button

I'm trying to make a play/pause button that toggles between custom images as it is pressed. Here is a snippet of the code.
Everything works fine but the button doesn't change. I've also tried using the .image property instead of the .setBackGroundImage method but then the button just goes blank on click.
Here is the code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var pauseImage:UIImage?
var playImage:UIImage?
#IBOutlet weak var btnPlayPause: UIBarButtonItem!
#IBOutlet weak var sldVolume: UISlider!
#IBAction func sldVolumeChanged(sender: AnyObject) {
audioPlayer.volume = sldVolume.value
}
#IBAction func actPressedPlayPause(sender: AnyObject) {
if audioPlayer.playing {
audioPlayer.pause()
btnPlayPause.setBackgroundImage(playImage, forState: .Normal, barMetrics: .Default)
} else {
audioPlayer.play()
btnPlayPause.setBackgroundImage(pauseImage, forState: .Normal, barMetrics: .Default)
}
}
#IBAction func actStopPressed(sender: AnyObject) {
audioPlayer.stop()
audioPlayer.currentTime = 0
}
override func viewDidLoad() {
super.viewDidLoad()
var pauseImagePath = NSBundle.mainBundle().pathForResource("pause", ofType: "png")
pauseImagePath = pauseImagePath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
pauseImage = UIImage(contentsOfFile: pauseImagePath!)
var playImagePath = NSBundle.mainBundle().pathForResource("play", ofType: "png")
playImagePath = playImagePath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
playImage = UIImage(contentsOfFile: pauseImagePath!)
var audioPath = NSBundle.mainBundle().pathForResource("minuetcminor", ofType: "mp3")
audioPath = audioPath!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var error : NSError? = nil
audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath!), error: &error)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
had the same problem here! Had two of us confused as to why it wasn't working, I think it's a change in Swift 2/Xcode 7 beta
Just do this:
btnPlayPause.image = UIImage(named: "myImage.png")
Hope that helps!
Seems like this question has got a lot of strange answers. The truth is there's no non-hacky way to change an image in already existing UIBarButtonItem. Instead, unfortunately, you have to re-create it.
I've made a helper method to do this:
func changeBarButtonItemImage(_ item: UIBarButtonItem, image: UIImage, navItem: UINavigationItem) -> UIBarButtonItem? {
let buttonItem = UIBarButtonItem(image: image, style: item.style, target: item.target, action: item.action)
buttonItem.isEnabled = item.isEnabled
if let leftIndex = navItem.leftBarButtonItems?.index(of: item) {
var items: [UIBarButtonItem] = navItem.leftBarButtonItems!
items[leftIndex] = buttonItem
navItem.leftBarButtonItems = items
return buttonItem
}
if let rightIndex = navItem.rightBarButtonItems?.index(of: item) {
var items: [UIBarButtonItem] = navItem.rightBarButtonItems!
items[rightIndex] = buttonItem
navItem.rightBarButtonItems = items
return buttonItem
}
return nil
}
Usage:
if let image = UIImage(named: showingFilter ? "icon_filter_active.png" : "icon_filter.png") {
if let buttonItem = changeBarButtonItemImage(self.filterButton, image: image, navItem: navigationItem) {
self.filterButton = buttonItem
}
}
Take note that I also copy isEnabled property, because, in my case, in some situations, I was changing button icon while in the disabled state.
The #IBAction should use sender as UIButton instead of AnyObject or Any. Also, once that is done, the button can be directly accessed from inside the function using sender. (This is Swift 3)
#IBAction func actPressedPlayPause(sender: UIButton) {
if audioPlayer.playing {
audioPlayer.pause()
sender.setBackgroundImage(UIImage(named: "playimage.png"), for: .normal)
} else {
audioPlayer.play()
sender.setBackgroundImage(UIImage(named: "pauseimage.png"), for: .normal)
}
}
Try using below line of code:
btnPlayPause.setImage(image, forState: .Normal)
this works for me.

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