If statements for code generated buttons, Swift - swift

I have read a lot on Staked Overflow and watched youtube videos about generating buttons with code, but I can't figure out how to have an if statement based off the button. This is nested inside of another statement because when one question is answered with the oringal yes or no buttons I have another question is asked.
I have:
var btn = UIButton(frame: CGRectMake(50, 50, 150, 20));
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
btn.setTitle("My Button Text!!", forState:UIControlState.Normal);
btn.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(btn);
func buttonTapped(sender: UIButton!) {
println("Button Tapped!!!")
}
But rather than printing "Button Tapped!!!" I get a "SIGABART" error. How could I use an if statement instead of a function one? Is there a better way to wright this function statement?
The full code is:
//
// ViewController.swift
// Living Vermont
//
// Created by Matthew Furtsch on 6/8/15.
// Copyright (c) 2015 Matthew Furtsch. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label1 = UILabel()
label1.text = "Is it a plant?"
label1.font = UIFont.systemFontOfSize(36)
label1.sizeToFit()
//Label location quardnets
label1.center = CGPoint(x: 100, y: 0)
view.addSubview(label1)
UIView.animateWithDuration(1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0, options: nil, animations: {
self.label1.center = CGPoint(x: 100, y: 0 + 40)
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func journal(sender: AnyObject)
{
}
#IBAction func noButton(sender: AnyObject)
{
label1.text = "no"
var btn = UIButton(frame: CGRectMake(50, 50, 150, 20));
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
btn.setTitle("My Button Text!!", forState:UIControlState.Normal);
btn.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(btn);
func buttonTapped(sender: UIButton!) {
println("Button Tapped!!!")
}
}
#IBAction func yesButton(sender: AnyObject)
{
label1.text = "yes"
}
}

My guess is that your buttonTapped function is nested inside another method like viewDidLoad. It needs to be a top-level method of your view controller class. Move your buttonTapped method up so it is inside your class, but not inside any methods inside your class.
You should edit your question and include the entire crash message you are getting, along with the stack trace. That might help us tell what's going wrong.

Related

child class inheriting from parent class not changing color

My swift code is trying to inherit view1 from parent class one to child class two. view1 is recongizined but when the code is run and the segue is applied nothing changes on the screen. view1 should change colors from pink to cyan. Its not I don't understand why the change is not being applied.
import UIKit
class one : UIViewController {
var view1 = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
[view1].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
view1.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
view1.backgroundColor = .systemPink
view.backgroundColor = .orange
view1.addTarget(self, action: #selector(move), for: .touchDown)
}
#objc func move(){
let vc = two()
vc.modalPresentationStyle = .overCurrentContext // actually .fullScreen would be better
self.present(vc, animated: true)
}
}
class two: one {
override func viewDidLoad() {
view1.backgroundColor = .cyan
}
}
Your code is working fine; the presentation of Two is happening. But you don't see anything, because:
The backgroundColor of Two's view is nil, i.e. .clear, so you don't see the background.
In Two, you never put anything into the interface. You talk to the button view1 in viewDidLoad, but unlike One's viewDidLoad, you never put that button into the interface. So you don't see the button (because it isn't there).
A minimal "fix" would be to call super in Two's viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad() // *
view1.backgroundColor = .cyan
}

Present viewController after touchUp GIDSignInButton()!

I make a Google Auth for my App, but I don't know how to present a new viewController after touchup GIDSignInButton!
Here how I make GIDSignInButton:
viewDidLoad (){
let googleBtn = GIDSignInButton()
googleBtn.frame = CGRect(x: 16, y: 500 + 66, width: view.frame.width - 32, height: 35)
view.addSubview(googleBtn)}
Here's a code example that will present a second, programmatically generated view controller using a standard UIButton. Obviously, you could do the same with your GIDSignInButton:
class MyViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let button = UIButton(frame: CGRect(x: 10, y: 250, width: self.view.frame.width - 20, height: 35))
button.setTitle("Go to VC2", for: .normal)
button.backgroundColor = UIColor.blue
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonClicked(sender: UIButton!)
{
let secondViewController = MySecondViewController()
present(secondViewController, animated: true, completion: {})
}
}
class MySecondViewController:UIViewController
{
override func viewDidLoad() {
self.view.backgroundColor = UIColor.darkGray
}
}
Note, however, that if you are presenting multiple views, you are advised to embed them in a Navigation Controller, as per Apple's Documentation

Use nested function as action for `UIButton`

I'm trying to add a target to my UIButton, but get an error when trying to use a nested function as its action.
Here's my code:
func createAddView() {
let addButton = UIButton()
func remove(sender: UIButton) {
print("Remove")
}
addButton.addTarget(self, action: #selector(remove(sender:)), for: .touchUpInside)
}
it is giving me this warning:
warning: No method declared with Objective-C selector 'remove'.
I need the ´remove´ function to be nested in the ´createAddView´function because I need to remove and fade out some other UIViews that is being create in the ´createAddView´ function
Anyone knows how I can do this?
You can't do this, cause func remove is exist only in func createAddView block.
There is no restriction to add one #selector() to multiple UIControl's. So you can declare func remove in class block and add it as #selector every time you create a new button.
Because the func remove is create within createAddView() method .
here´s the fixed code :
func createAddView() {
let view = UIView() //added for testing purposes
view.frame = CGRect(x: 0, y: 0, width: 320 , height: 640) //added for testing purposes
let addButton = UIButton()
addButton.frame = CGRect(x: 0, y: 0, width: 100, height: 50) //added for testing purposes
view.addSubview(addButton)
addButton.addTarget(self, action: #selector(remove(sender:)), for: .touchUpInside)
}
func remove(sender: UIButton) {
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in
print("Add")
}) {(Bool) -> Void in
print("Done")
}
}

Swift - Getting tap location on a button which was created through custom UIView class

I have a main scrollerview in my main UIViewController and a custom UIView class. This custom UIView class has few lines of code to create Button and Label programmatically. The action to be performed by Button click is working fine, but I also need to get the exact tap location (CGPoint) on the button as the button is long and tap x-coordinate is required for next actions. I tried few solutions got from stackoverflow and is working for other objects like Label and Imageview but doesn't work for button.
My custom UIView class:
import UIKit
class DrawProj: UIView {
override func drawRect(rect: CGRect) {
let button = UIButton(type: .System)
button.frame = CGRectMake(24, 15, linewidth - 25, 20)
button.backgroundColor = UIColor.orangeColor()
button.addTarget(nil, action: "onButtonTap:", forControlEvents: .TouchUpInside)
self.addSubview(button)
}
}
And Code in main Viewcontroller
let DrawProjectLanes = DrawProj(frame: CGRect(x: startx, y: starty, width: endx , height: 50))
DrawProjectLanes.backgroundColor = UIColor.clearColor()
DrawProjectLanes.userInteractionEnabled = true
MainScroller.addSubview(DrawProjectLanes)
You should override touchesBegan for this to work:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
Then declare your button subview as a property:
class DrawProj: UIView {
var button: UIButton!
override func drawRect(rect: CGRect) {
button = UIButton(type: .System)
button.frame = CGRectMake(24, 15, linewidth - 25, 20)
button.backgroundColor = UIColor.orangeColor()
button.addTarget(nil, action: "onButtonTap:", forControlEvents: .TouchUpInside)
self.addSubview(button)
}
}
In touchesBegan, do this to get the x position of the tap, relative to the button's frame:
let posX = touches.first!.locationInView(button).x
Then, you can use this posX variable however you want.
How to instantiate a view controller:
In the storyboard, select the VC that you would like to present. Go to the identity inspector, set a Storyboard ID for the VC:
Then in code,
let sb = UIStoryboard(name: "Main", bundle: nil)
let viewController = sb.instantiateViewControllerWithIdentifier("put the storyboard ID that you set earlier here")
let topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController?.presentationController
topViewController?.presentViewController(viewController, animated: true, completion: nil)

swift UIview removeFormSuperview

this is a test code,I want to add uiview to storyBoard ,and wait 1 second, and remove it .but the uiview doesn't appear , the code is down
var uiview1 = UIView()
uiview1.frame = CGRectMake(0, 0, 50, 50)
uiview1.backgroundColor = UIColor.blackColor()
self.view.addSubview(uiview1)
sleep(1)
uiview1.removeFromSuperview()
sleep() is not a good idea in this way. It will become totally unresponsive and block. Use NSTimer.scheduledTimerWithTimeInterval instead.
class ViewController: UIViewController {
var uiview1 = UIView()
override func viewDidLoad() {
super.viewDidLoad()
uiview1.frame = CGRectMake(0, 0, 50, 50)
uiview1.backgroundColor = UIColor.blackColor()
self.view.addSubview(uiview1)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("dismissView"), userInfo: nil, repeats: false)
}
func dismissView() {
uiview1.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}