UIbutton remove from MenuScene before I jump into GameScene, or when I don't remove, the button is visible in GameScene, but I draw in MenuScene, why is that? What is the best way to create buttons and change the images of button?
The code is:
var button: UIButton!
button = UIButton()
var buttonFrame = self.view!.frame
button?.frame = CGRectMake(0, 0, 200, 100)
let buttonImage = UIImage(named: "PlayButton")
let buttonClick = UIImage(named: "PlayButton-click")
button!.setImage(buttonImage, forState: UIControlState.Normal)
button!.setImage(buttonClick, forState: UIControlState.Highlighted)
button!.addTarget(self, action: "PlayButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(button)
func PlayButtonClick(sender: UIButton) {
self.view?.presentScene(GameScene(size:self.size),transition: .crossFadeWithDuration(1.2))
button.removeFromSuperview()
}
Try that in PlayButtonClick Method:
sender.hidden = true
This should probably do the trick.
button.hidden = true, or sender.hidden = true,
This hide the uibutton , but button is hide very early, before i enter the GameScene state, and i see that..
Related
let button = UIButton()
button.setImage(UIImage(named: "coin_icon"), forState: UIControlState.Normal)
button.addTarget(self, action:#selector(Profile.goCoin), forControlEvents: UIControlEvents.TouchDragInside)
button.frame=CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
My code is this to add a bar button on navigation bar.
However, i need to change the title of button in a function
func changetitle() {
self.navigationItem.rightBarButtonItem?.title = "Change"
}
I tried this one but didn't work.
How can i change the title of this button?
You need to access the UIButton from the UIBarButtonItem and change the title of the UIButton.
func changetitle() {
let item = self.navigationItem.rightBarButtonItem!
let button = item.customView as! UIButton
button.setTitle("Change", for: .normal)
}
I have the following code.
import UIKit
class ViewController: UIViewController {
var button : UIButton?
override func viewDidLoad() {
super.viewDidLoad()
button = UIButton.buttonWithType(UIButtonType.System) as UIButton?
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I get the following error
ERROR:
'AnyObject' is not convertible to 'UIButton?'
I know I might be doing something fundamentally wrong. I would like to know what that is.
According to me:
I have declared button as an Optional UIButton
- Which I think means, that the value of button can be unset or nil
Therefore,
while initialising it the type is mentioned as UIButton?
Is this it right way ?
You can't cast to an optional UIButton in the way you're doing it. The correct way to cast to an optional UIButton is:
button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
Interpret this as: This cast can either return nil or an UIButton object, resulting in an optional UIButton object.
Follow the below code
var myBtn = UIButton.buttonWithType(UIButtonType.System) as UIButton
//OR
var myBtn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
//OR
var myBtn = UIButton()
myBtn.setTitle("Add Button To View Controller", forState: .Normal)
myBtn.setTitleColor(UIColor.greenColor(), forState: .Normal)
myBtn.frame = CGRectMake(30, 100, 200, 400)
myBtn.addTarget(self, action: "actionPress:", forControlEvents: .TouchUpInside)
self.view.addSubview(myBtn)
//Button Action
func actionPress(sender: UIButton!)
{
NSLog("When click the button, the button is %#", sender.tag)
}
Please try below code:
var button = UIButton(frame: CGRectMake(150, 240, 75, 30))
button.setTitle("Next", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.backgroundColor = UIColor.greenColor()
self.view.addSubview(button)
This code should do the job.
button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
In this case the force cast done with the ! is a safe option because the documentation does guarantee that the method returns a UIButton.
You can also create the button during the declaration of the property:
class ViewController: UIViewController {
var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
...
This way there is no need to declare the property as an optional type.
I used the following tutorial to programmatically create a UIBarButtonItem in Swift, but the icon isn't properly aligned to the border. Here's the code for the button. Can anyone tell me how to modify the code below to properly align the UIBarButtonItem Image?
The 1st image shows the location of the programmatically created uibarbuttonitem, and the 2nd image shows the uibarbuttonitem created from storyboard. I want the programmatically created uibarbuttonitem to look like uibarbuttonitem created using storyboard. Thanks for the help!
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.targetForAction("actioncall:", withSender: nil)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
self.navigationItem.leftBarButtonItem = leftBarButtonItem
Also, how do I properly set the action for when the uibarbuttontiem is pressed? I tried the following but it's never called.
func actioncall(sender: AnyObject){
println("action")
}
Edit 1: I updated the code as follows thanks to agy's response.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
if (cond){
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -20; // set the value you need
self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]
}
}
func actioncall(sender: UIButton!){
println("action")
}
but the action still fails. The app crashes when I press the uibarbuttontiem and I get the following error message
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.ProfileViewController actioncall:]: unrecognized selector sent to instance 0x7a07a470'
What's the correct function for the action?
Edit 2: The actioncall is in the same class as where I'm creating the UIBarButtonItem. I'm setting the leftbarbutton on viewwillappear because depending on who views this viewcontroller, the option to go back will replace the previous option located on the leftbarbutton.
Try adding a negative spacer, and change the method targetForAction for addTarget:
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -5; // set the value you need
self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]
func actioncall(sender: UIButton!){
print("Called")
}
Using Swift, how do I make a:
Button with words "start", that changes to "pause" and vice versa when tapped? Not just once, but can be done infinitely? (e.g. in a stopwatch app)
Custom image button that changes between 2 image when tapped, that can also be done (tapped & change) infinitely?
Step 1: Create a Bool variable
var isPlaying:Bool = false
Step 2: Connect your button with this IBAction method:
#IBAction func btnStartStop(sender: UIButton) {
if isPlaying{
isPlaying = false
sender.setTitle("Pause", forState: UIControlState.Normal)
sender.setImage(pauseImage, forState: .Normal)
//Pause Stopwatch
}
else{
isPlaying = true
sender.setTitle("Play", forState: UIControlState.Normal)
sender.setImage(playImage, forState: .Normal)
//Play Stopwatch
}
}
In your storyboard, set the Default state title to "Start" and the Selected state title to "Pause"
Or alternatively, if you're doing it in code:
startPauseButton.setTitle("Start", forState: .Normal)
startPauseButton.setTitle("Pause", forState: .Selected)
In your IBAction func, toggle the button.selected property between true & false
#IBAction func toggleStopwatch(button:UIButton) {
if button.selected {
// Pause the stopwatch
} else {
// Start the stopwatch
}
button.selected = !button.selected
}
You can also set different images for different states: Default, Highlighted, Selected, Disabled
In the #IBAction of the button (assuming you are using storyboards), you change the title or image of the button to what you want. You can also check for the title or image and perform an action based on what you have.
#IBAction func pressbutton(sender: UIButton) {
switch sender.titleLabel?.text {
case "Play":
play()
case "Pause":
pause()
default:
other()
}
sender.titleLabel?.text = "Whatever you want"
}
Or with images (assuming you have an images array somewhere that stores the images, which you should):
#IBAction func pressbutton(sender: UIButton) {
switch sender.imageView!.image! {
case images[0]:
play()
case images[1]:
pause()
default:
other()
}
sender.imageView?.image = UIImage(...)
}
Try this....
#IBAction func btnStopWatch(sender: UIButton) {
if btnStopWatch.selected == true {
btnStopWatch.setTitle("stop", forState: UIControlState.Normal)
btnStopWatch.setImage(stopImage, forState: UIControlState.Normal)
btnStopWatch.selected = false
} else {
btnStopWatch.setTitle("start", forState: UIControlState.Normal)
btnStopWatch.setImage(startImage, forState: UIControlState.Normal)
btnStopWatch.selected = true
}
}
#1. Toggle a UIButton title
With Swift 3, UIButton has a method called setTitle(_:for:). setTitle(_:for:) has the following declaration:
func setTitle(_ title: String?, for state: UIControlState)
Sets the title to use for the specified state.
The following Playground code shows how to use setTitle(_:for:) in order to toggle the title of a button according to its state:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let button = UIButton(type: UIButtonType.system)
button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)
// Set button's states
button.setTitle("Start", for: UIControlState.normal)
button.setTitle("Pause", for: UIControlState.selected)
// set layout
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
}
/// trigger action when button is tapped
func toggle(sender: UIButton) {
sender.isSelected = !sender.isSelected
print("Button state: \(sender.isSelected)")
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc
Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor
#2. Toggle a UIButton image
UIButton has a method called setImage(_:for:). setImage(_:for:) has the following declaration:
func setImage(_ image: UIImage?, for state: UIControlState)
Sets the image to use for the specified state.
The following Playground code shows how to use setImage(_:for:) in order to toggle the title of a button according to its state:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let button = UIButton()
button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)
// Set button's states
button.setImage(UIImage(named: "on.png"), for: UIControlState.normal)
button.setImage(UIImage(named: "off.png"), for: UIControlState.selected)
// set layout
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: 100)
let widthConstraint = button.widthAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, heightConstraint, widthConstraint])
}
/// trigger action when button is tapped
func toggle(sender: UIButton) {
sender.isSelected = !sender.isSelected
print("Button state: \(sender.isSelected)")
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc
Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor
var ExitImg: UIImage!
var ExitButton: UIButton!
func missileHitAction(sender:UIButton!)
{
self.view.viewWithTag(12221)?.removeFromSuperview()
ExitImg = nil
ExitButton = nil
}
override func viewDidLoad() {
super.viewDidLoad()
ExitImg = UIImage(contentsOfFile: "/Users/Joca/Desktop/Game_dev/missile_gun1")
ExitButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
ExitButton.frame = CGRectMake(5, 285, 70, 30)
ExitButton.imageView?.tag = 12221
ExitButton.setBackgroundImage(ExitImg, forState: UIControlState.Normal)
ExitButton.addTarget(self, action: "missileHitAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(ExitButton)
}
This is a sample test project for deallocating buttons, on button press button should be deallocated, but its not :(
You are creating a button, but are not setting its tag. Instead, you are setting its image view's tag. Instead of:
ExitButton.imageView?.tag = 12221
I think you intended:
ExitButton.tag = 12221