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.
Related
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: [])
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 a tableView, and when the user taps a cell, it opens an alert box with the options "Close" and "Search". The handler for "Search" is shown below as func searchSongAction.
This presents a new viewcontroller (embedded in a Nav Bar) that searches the song online. In this new viewcontroller, Search, there are 2 functions: one searches the song currently playing and the other searches the song that the user asked to search from the tableView alert.
I am trying to pass the data from the cell into the Search class, but I keep coming up short. I feel like what I have is correct, but that is obviously not he case.
Any ideas?
Ask me if you need any more information.
History.swift
func searchSongAction(alert: UIAlertAction!) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("Search") as! Search
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationNavigationController = segue.destinationViewController as! UINavigationController
let targetController = destinationNavigationController.topViewController as! Search
targetController.searchType = "Previous"
targetController.songNowText = self.songToSearch
targetController.artistNowText = self.artistToSearch
}
Search.swift
class Search: UIViewController {
var songNowText = ""
var artistNowText = ""
var searchType = ""
override func viewDidLoad() {
super.viewDidLoad()
if searchType == "Previous" {
searchSongPrevious()
} else {
searchSongNow()
}
}
}
You're not actually performing a Segue from your searchSongAction: function, so I'm guessing that prepareForSegue:sender: isn't actually being called and therefore the setup is not running.
Try assigning searchType, songNowText and artistNowText on vc inside of searchSongAction::
func searchSongAction(alert: UIAlertAction!) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("Search") as! Search
//Setup the properties
vc.searchType = "Previous"
vc.songNowText = self.songToSearch
vc.artistNowText = self.artistToSearch
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
As a side note, typically you'll want to call super's implementation of a function when overriding it (you have neglected to do this in prepareForSegue:sender:)
So I just did a tutorial on adding a blurry sidebar menu. I replicated the code but I cant seem to find out how to call my other ViewControllers I made in storyboard mode.
I have created files and linked them to UIViewControllers. But when I try to call that ViewController with my sidebar menu I'm getting a black screen.
Here is the link of the files I used to follow along http://goo.gl/ULWxJh
And here is the link of the youtube video I followed along with http://www.youtube.com/watch?v=qaLiZgUK2T0
Not sure why! Any help would be greatly appreciated
class ViewController: UIViewController, SideBarDelegate {
var sideBar:SideBar = SideBar() // Side Bar
override func viewDidLoad() {
super.viewDidLoad()
// Side bar action and text
sideBar = SideBar(sourceView: self.view, menuItems: ["Home", "Business Directory", "Classifieds", "Featured News", "Jobs", "Restaurants", "Sports"])
sideBar.delegate = self
}
// Side Bar funcion
func sideBarDidSelectButtonAtIndex(index: Int) {
if index == 0{
let vc = ViewController()
self.presentViewController(vc, animated: true, completion: nil)
}else if index == 1{
let vc = businessDirectoryVC()
self.presentViewController(vc, animated: true, completion: nil)
}
}
}
Add a Storyboard ID (in this case "view") to the View Controller in your Main Storyboard and then add the following to the file from where you want to call the sidebar from:
func sideBarDidSelectButtonAtIndex(index: Int) {
if index == 0 {
let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let showView = storyBoard.instantiateViewControllerWithIdentifier("view") as! ViewController
self.presentViewController(showUebersicht, animated:true, completion:nil)
}
}
Value "0" stands for the first item in the sidebar. Change the value for another value of the array where the items of the sidebar are stored.
I have this code that opens up a popover element at the "sender" location, i.e. the button that was pressed. How can I make this function call when a statusItem is clicked, so that the popover comes down from the status/menu bar?
#IBAction func togglePopover(sender: AnyObject) {
if !(popoverIsOpen) {
myPopover.showRelativeToRect(sender.bounds, ofView: popoverButton, preferredEdge: NSRectEdge(3))
popoverIsOpen = true
}
else {
myPopover.close()
popoverIsOpen = false
}
}
I am currently using NSPopover and NSStatusItem.
edit: The changelog for Xcode 6 beta 4 added NSStatusItem.button and softly deprecated the previous form of calls like NSStatusItem.action, NSStatusItem.title, NSStatusItem.target, etc.
The documentation now reads
NSStatusItem.button
The button that is displayed in the status bar. This is created automatically on the creation of the StatusItem. Behavior customization for the button, such as image, target/action, tooltip, can be set with this property.
I was able to reach an implementation shown below, using the new NSStatusBarButton visual representation of an NSStatusBarItem. In this example, my .xib file has the NSPopover element already connected to a view, which isn't shown here.
#IBOutlet weak var myPopover: NSPopover!
var statusBar: NSStatusItem!
var popoverIsOpen = false
#IBAction func togglePopover(sender: AnyObject) {
if !(popoverIsOpen) {
myPopover.showRelativeToRect(sender.bounds, ofView: statusBar.button, preferredEdge: NSRectEdge(3))
popoverIsOpen = true
}
else {
myPopover.close()
popoverIsOpen = false
}
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
//initialize menu bar icon
statusBar = NSStatusBar.systemStatusBar().statusItemWithLength(CGFloat(48))
statusBar.button.title = "Your App Title"
statusBar.button.appearsDisabled = false
statusBar.button.action = Selector("togglePopover:")
statusBar.button.target = self
}