In my swift project I have a button and I want to print on a label how much time this button has been pressed.
How can I resolve this problem?
Adding to DHEERAJ's answer, you just need to add following code in func pressed(sender: UIButton!) to achieve what you need:
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
let dateString = dateFormatter.stringFromDate(date)
yourLabelName.text = dateString
Hope this might help.
To show how many times the button has been clicked you could class variable.
class SampleViewController: UIViewController {
var counter : Int!
#IBOutlet weak var yourLabelName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
counter = 1
let myFirstButton = UIButton(frame: CGRectMake(10, 50, 320, 40))
myFirstButton.setTitle("Tap Me", forState: .Normal)
myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myFirstButton.addTarget(self, action: "pressed:",forControlEvents: .TouchUpInside)
self.view.addSubview(myFirstButton)
}
func pressed(sender: UIButton!)
{
yourLabelName.text = "Pressed : \(counter)"
counter = counter + 1
}
}
Here is how button is created programmatically and prints a text in label when button is pressed.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myFirstButton = UIButton()
myFirstButton.setTitle("Tap Me", forState: .Normal)
myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myFirstButton.frame = CGRectMake(10, 50, 320, 40)
myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(myFirstButton)
}
func pressed(sender: UIButton!)
{
yourLabelName.text=#"Your Text is here"
}
Related
SquareBox.swift
class SquareBox {
func createBoxes() {
for _ in 0..<xy {
let button = UIButton()
button.backgroundColor = .white
button.setTitleColor(UIColor.black, for: .normal)
button.layer.borderWidth = 0.5
button.layer.borderColor = UIColor.black.cgColor
stack.addArrangedSubview(button)
button.addTarget(self, action: #selector(click(sender:)) , for: .touchUpInside)
}
}
#objc func click(sender : UIButton) {
print("Click")
}
}
ViewController.swift
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let boxRow = SquareBox()
boxRow.createBoxes()
}
}
Also I've tried #IBAction instead of #objc, it doesn't work, but if I use "click" function in ViewController.swift that I created this object, it's working but I need this function inside of this class.
Now that you have posted relevant information in your question, the problem is quite clear. You have a memory management issue.
In your GameViewController's viewDidLoad you create a local instance of SquareBox. This local instance goes out of scope at the end of viewDidLoad. Since there is no other reference to this instance, it gets deallocated at the end of viewDidLoad.
Since the instance of SquareBox has been deallocated, it is not around to act as the button's target. And your click method is never called.
The solution is to keep a reference in your view controller:
class GameViewController: UIViewController {
let boxRow = SquareBox()
override func viewDidLoad() {
super.viewDidLoad()
boxRow.createBoxes()
}
}
var btnfirst:UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
btnfirst = UIButton(type: .system)
btnfirst.setTitle("Press", for: .normal)
btnfirst.setTitleColor(.red, for: .normal)
btnfirst.frame = CGRect(x: 100, y: 200, width: 100, height: 30)
btnfirst.addTarget(self, action: #selector(benpress( sender:)),for: .touchUpInside)
self.view.addSubview(btnfirst)
}
func benpress( sender :UIButton)
{
//Your Code Here
}
For those who did not find a solution, here is mine.
If you constructed your UIButton as
let button: UIButton = {
return UIButton()
}()
Just convert those into
lazy var button: UIButton = {
return UIButton()
}()
I think this is because of somewhat deallocation as mentioned above.
button.addTarget(self, action:#selector(self.click), for: .touchUpInside)
func click(sender : UIButton) {
// code here
}
I guess the issue is how you are setting up layout of your buttons.
Try this:
func createBoxes() {
stack.backgroundColor = UIColor.red
for _ in 0..<xy {
// Create the button
let button = UIButton()
button.backgroundColor = UIColor.red
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
// Setup the button action
button.addTarget(self, action: #selector(SquareBox.click(sender:)), for: .touchUpInside)
// Add the button to the stack
stack.addArrangedSubview(button)
}
}
#objc func click(sender : UIButton) {
print("Click")
}
button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
func buttonTapped(sender : UIButton) {
// code here
}
Replace with this :
btn.addTarget(self, action: #selector(self.click(sender:)), for: .touchUpInside)
I think something else effect to your selector method try to find in your code because your code also working in my project.
I am trying to create dynamic radio buttons based on Firebase data. I am hoping to arrange the buttons in a vertical stack, and essentially when they are clicked I would hope for them to disappear and display another view:
class PollController: UIViewController {
#IBOutlet weak var passLabel: UILabel!
#IBOutlet weak var pollImage: UIImageView!
var ref: FIRDatabaseReference!
var pollRef: FIRDatabaseReference!
var pass = ""
var passedImageURL = ""
var posX = 0;
var posY = 0;
var buttons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
pollRef = ref.child("Polls").child(pass)
passLabel.text = pass
pollImage.sd_setImage(with: URL(string: passedImageURL), placeholderImage: UIImage(named: "test"))
pollRef.observe(FIRDataEventType.value, with: {(snapshot) in
let numberOfChildren = snapshot.childSnapshot(forPath: "answers").childrenCount
self.passLabel.text = String(numberOfChildren)
print(numberOfChildren)
var stackView = UIStackView(arrangedSubviews: self.buttons)
// create button1
for x in 0..<numberOfChildren {
let button = UIButton(frame: CGRect(x: self.posX, y: self.posY, width: 60, height: 20))
button.setTitleColor(UIColor.black, for: .normal)
button.setTitle("No", for: .normal)
button.setImage(UIImage(named: "checkbox untick.png")!, for: .normal)
// if the selected button cannot be reclick again, you can use .Disabled state
button.setImage(UIImage(named: "checkboxredtick.png")!, for: .selected)
button.tag = Int(x)
button.addTarget(self, action: #selector(self.buttonAction(sender:)), for: .touchUpInside)
stackView.addSubview(button)
self.buttons.append(button)
// create other buttons and add into buttons ...
}
})
// Do any additional setup after loading the view.
}
func buttonAction(sender: UIButton!){
for button in buttons {
button.isSelected = false
}
sender.isSelected = true
// you may need to know which button to trigger some action
// let buttonIndex = buttons.indexOf(sender)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If you are using SWIFT 3.0 or later,
Then you must define add target method like below as _: is missing in the selector parameter.
button.addTarget(self, action: #selector(buttonAction(_:)), for: .TouchUpInside)
Also check id you have declares myStackview variable here. if you declared then try to add it as :
self.myStackview
Your button declaration is func buttonAction(sender: UIButton!). Note that there are no underscore before sender. This means that you need to specify the name of the argument when you call the function. Replace the underscore in the selector with the argument name sender
button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
You can also add an underscore in front of the argument name in the function.
func buttonAction(_ sender: UIButton!)
Also, I noticed that the code is in Swift 3 seeing most of the syntax. So, the control event for touch up inside in Swift 3 is touchUpInside and not TouchUpInside
I have a class like this,
import UIkit
class One {
let btn = UIButton()
override func viewDidLoad(){
super.viewDidLoad()
btn.frame = CGRectMake(10, 20, 30, 30)
btn.setTitle("Go", forState: UIControlState.Normal)
btn.addTarget(self, action: "goToClassTwo", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func goToClassTwo(){
if(AppGlobals().getIsFromDiffView()){
let difView = UINavigationController(rootViewController: DiffView())
difView.pushViewController(Two(), animated: true)
}else{
self.navigationController?.pushViewController(Two(), animated: true)
}
}
}
A setter/getter class like this,
class AppGlobals: NSObject {
var isFromDiffView = false
func setIsFromDiffView(val: Bool){
isFromDiffView = val
}
func getIsFromDiffView() -> Bool {
return isFromDiffView
}
}
And I have another class like this,
class DiffView {
let btn = UIButton()
override func viewDidLoad(){
super.viewDidLoad()
btn.frame = CGRectMake(10, 20, 30, 30)
btn.setTitle("Push", forState: UIControlState.Normal)
btn.addTarget(self, action: "btnAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func btnAction(){
AppGlobals().setIsFromDiffView(true)
One().goToClassTwo()
}
}
I am facing a problem here. When the 'Go' button in the class 'One' is tapped, then the 'Two' view controller is shown. But when I tap on the 'Push' button in the class 'DiffView' is tapped, the 'Two' view controller is not being shown.
I have checked setting breakpoints. The control does come to the goToClassTwo function in the class 'One' and the if path is being executed. But the 'Two' view controller is not shown. difView.pushViewController is called. But it is not pushing to the next view.
NOTE: I am not using storyboard
Any help would be appreciated!
This is the updated code.
Code for class 'One':
import UIKit
class One {
let btn = UIButton()
override func viewDidLoad(){
super.viewDidLoad()
btn.frame = CGRectMake(10, 20, 30, 30)
btn.setTitle("Go", forState: UIControlState.Normal)
btn.addTarget(self, action: "goToClassTwo", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func goToClassTwo(){
if(AppGlobals().getIsFromDiffView()){
//Using the navigation controller of DiffView
AppGlobals().getController().pushViewController(Two(), animated: true)
}else{
self.navigationController?.pushViewController(Two(), animated: true)
}
}
}
setter/getter class:
class AppGlobals: NSObject {
var isFromDiffView = false
var cntrlr: UINavigationController!
func setIsFromDiffView(val: Bool){
isFromDiffView = val
}
func getIsFromDiffView() -> Bool {
return isFromDiffView
}
//Setting and getting DiffView Navigation controller
func setController(cntrl: UINavigationController){
cntrlr = cntrl
}
func getController() -> UINavigationController {
return cntrlr
}
}
DiffView class:
class DiffView {
let btn = UIButton()
override func viewDidLoad(){
super.viewDidLoad()
btn.frame = CGRectMake(10, 20, 30, 30)
btn.setTitle("Push", forState: UIControlState.Normal)
btn.addTarget(self, action: "btnAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func btnAction(){
AppGlobals().setIsFromDiffView(true)
//Setting the navigation controller
AppGlobals().setController(self.navigationController!)
One().goToClassTwo()
}
}
With this updated code, class 'Two' view controller is being displayed.
Thank you #zp_x for your help.
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
In Swift, I have a view with three objects. I want the button and label to be on top of the image. This is a concept like maybe layers in Photoshop. Currently, the image is on top of the button and label, so you can not see the button and label. How is this done?
My code is here:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myFirstLabel = UILabel()
let myFirstButton = UIButton()
let myFirstImage = UIImage(named: "1792614.jpg")
let myFirstImageView = UIImageView(image: myFirstImage)
myFirstLabel.text = "I made a label on the screen #toogood4you"
myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstLabel.textColor = UIColor.redColor()
myFirstLabel.textAlignment = .Center
myFirstLabel.numberOfLines = 5
myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
myFirstButton.setTitle("✸", forState: .Normal)
myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myFirstButton.frame = CGRectMake(160, 284, 50, 50)
myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstImageView)
}
func pressed(sender: UIButton!) {
var alertView = UIAlertView()
alertView.addButtonWithTitle("Ok")
alertView.title = "title"
alertView.message = "message"
alertView.show()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The answer is here:
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstImageView)
When you add a subview, it always gets put at the top, to achieve what you want, add the view you want at the bottom first, and the one you want on top last:
self.view.addSubview(myFirstImageView)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstLabel)
You're adding the views in this order:
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstImageView)
which means myFirstImageView is going to be on top. Reversing the order of the addSubview calls will do what you want.