Insert a button and load a second view programmatically using Swift - ios

I want to, programmatically, add a button to a view and then when the user press this button a second view called "Giraanam" is loaded. I managed to write the code to display the button, but I cannot discover how to make it load the second view... Can anyone please help me?
The code I tried so far is:
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(20, 25, 34, 34)
button.backgroundColor = UIColor.greenColor()
button.setBackgroundImage(UIImage(named:"Back_Resultados.png"),forState: UIControlState.Normal)
button.addTarget(self, action: "Giraanam", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)

You need to implement function Giraanam to create a new view and add to another view. Example:
func Giraanam() {
let newView = UIView()
// customise your view
self.view.addSubview(newView)
}

Related

creating customized popuser using label and buttons (swift/ios)

I'm trying to create custom popopview using labels and button, something like this;
First, created a label with opac background;
let opacLabel = UILabel(frame:CGRectMake(0,0,self.screenWidth,self.screenHeight))
opacLabel.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.9)
view.addSubview(opacLabel)
then a layer for popup view;
let categoryMenuLabel = UILabel(frame: CGRectMake(10,40,100,300))
categoryMenuLabel.backgroundColor = UIColor.whiteColor()
categoryMenuLabel.clipsToBounds = true
categoryMenuLabel.layer.cornerRadius = 7
and then a button
let saveButton = UIButton(frame: CGRectMake(spaceX,400,150,40))
saveButton.backgroundColor = UIColor.lightGrayColor()
saveButton.titleLabel!.font = UIFont(name: "Helvetia", size: 25)
saveButton.setTitle("Save", forState: UIControlState.Normal)
saveButton.addTarget(self, action: "categorySaveButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
categoryMenuLabel.addSubview(saveButton)
finally added categoryMenuLabel to main view and changed order;
self.view.addSubview(categoryMenuLabel)
self.view.bringSubviewToFront(opacLabel)
self.view.bringSubviewToFront(categoryMenuLabel)
With this configuration, when I try to press button, instead of button, it pressed the table cell under label.
I also couldn't manage to disable touch actions outside of the label.
Just enable user interaction on the label. It's off by default, and that prevents it's children from receiving any user interaction, as well:
categoryMenuLabel.userInteractionEnabled = true

How do you switch between Controllers upon Clicking a programmed button in Swift XCode

EDIT
This is my current code with the programmed buttons.
override func viewDidLoad() {
super.viewDidLoad()
self.playVideo()
var filter = UIView()
filter.frame = self.view.frame
filter.backgroundColor = UIColor.orangeColor()
filter.alpha = 0.15
self.view.addSubview(filter)
// Do any additional setup after loading the view, typically from a nib.
//Add Images
var logoImage : UIImageView
logoImage = UIImageView(frame:CGRectMake(136, 50, 102, 104));
logoImage.image = UIImage(named:"patchicon.png")
self.view.addSubview(logoImage)
var textLogo : UIImageView
textLogo = UIImageView(frame:CGRectMake(51, 0, 273, 371));
textLogo.image = UIImage(named:"logopatch.png")
self.view.addSubview(textLogo)
//Add Buttons
let buttonLogin = UIButton.buttonWithType(.Custom) as! UIButton
buttonLogin.frame = CGRectMake(16, 519, 343, 60)
buttonLogin.layer.cornerRadius = 0.2 * buttonLogin.bounds.size.width
buttonLogin.addTarget(self, action: "buttonTouched", forControlEvents: UIControlEvents.TouchUpInside)
buttonLogin.setImage(UIImage(named:"loginButton.png"), forState: .Normal)
view.addSubview(buttonLogin)
let buttonRegister = UIButton.buttonWithType(.Custom) as! UIButton
buttonRegister.frame = CGRectMake(16, 587, 343, 60)
buttonRegister.layer.cornerRadius = 0.2 * buttonRegister.bounds.size.width
buttonRegister.addTarget(self, action: "buttonTouched2", forControlEvents: UIControlEvents.TouchUpInside)
buttonRegister.setImage(UIImage(named:"registerButton.png"), forState: .Normal)
view.addSubview(buttonRegister)
}
func buttonTouched()
{
performSegueWithIdentifier("loginTouched", sender: nil)
}
func buttonTouched2()
{
performSegueWithIdentifier("registerTouched", sender: nil)
}
This is what my Storyboard looks like:
http://i.stack.imgur.com/MlEhI.png
How can I program these buttons further to switch into new view controllers? For instance, I want to click the register button and I want the current MainViewController to switch to a new one that will have the information for the user to sign up and so forth...
Thanks!
First, you need to add a target to the button:
buttonLogin.addTarget(self, action: "buttonTouched", forControlEvents: UIControlEvents.TouchUpInside)
And then, add this function:
func buttonTouched()
{
println("touched")
}
To switch to a new view controller, take a look at this
Well, to switch to a "new" view controller, you need to first create that view controller in your storyboard. After that, do you see that line that links the main view controller to the other two? Click that line and go to "Attributes Inspector". In the identifier blank space, fill with whatever you want and then, in the button that you created programmatically, you need to set this:
performSegueWithIdentifier("whateverYouWant", sender: self)
Oh, and don't forget this step: select your main view controller, go to Editor > Embed In > Navigation Controller. If you don't do this, your application will crash.
Hope that helps!
EDIT: Try this:
Write some function like this outside the viewDidLoad method:
func segueToNextVC(sender: UIButton!) {
println("Button pressed, let's see what happens!")
performSegueWithIdentifier("whateverYouWant", sender: self)
}
Then, in your button in viewDidLoad, do like this:
buttonLogin.addTarget(self, action: "segueToNextVC:", forControlEvents: UIControlEvents.TouchUpInside)
Note: Don't forget the : in segueToNextVC:, that's important!
add target to your button..
buttonLogin.addTarget(self, action: "btnpressed:", forControlEvents: .TouchUpInside)
Vtwot is my Second viewController and its Storyboard Id is ViewTwoId..
make UIButtons action like these..
func btnpressed(sender: UIButton!)
{
let jj = self.storyboard!.instantiateViewControllerWithIdentifier("ViewTwoId") as! Vtwot
self.navigationController!.pushViewController(jj, animated: true)
}
i hope it helps..

How to change UIButton label programmatically

When I first run my app, I retrieve a number from my server and display it for my UIButton label. Think of this as a notification number displayed on a red UIButton.
When I remove a notification within the app, I want my UIButton label decrement by 1. I am able to get the decremented number from the server after I delete a notification, but I can't display this new number on the UIButton. The button always displays the number when the app is first fired.
I call makeButtonView() method after I remove a notification to update the UIButton
func makeButtonView(){
var button = makeButton()
view.addSubView(button)
button.tag = 2
if (view.viewWithTag(2) != nil) {
view.viewWithTag(2)?.removeFromSuperview()
var updatedButton = makeButton()
view.addSubview(updatedButton)
}else{
println("No button found with tag 2")
}
}
func makeButton() -> UIButton{
let button = UIButton(frame: CGRectMake(50, 5, 60, 40))
button.setBackgroundImage(UIImage(named: "redBubbleButton"), forState: .Normal)
API.getNotificationCount(userID) {
data, error in
button.setTitle("\(data)", forState: UIControlState.Normal)
}
button.addTarget(self, action: "targetController:", forControlEvents: UIControlEvents.TouchUpInside)
return button
}
Use this code for Swift 4 or 5
button.setTitle("Click Me", for: .normal)
I need more information to give you a proper code. But this approach should work:
lazy var button : UIButton = {
let button = UIButton(frame: CGRectMake(50, 5, 60, 40))
button.setBackgroundImage(UIImage(named: "redBubbleButton"), forState: .Normal)
button.addTarget(self, action: "targetController:", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
func makeButtonView(){
// This should be called just once!!
// Likely you should call this method from viewDidLoad()
self.view.addSubview(button)
}
func updateButton(){
API.getNotificationCount(userID) {
data, error in
// be sure this is call in the main thread!!
button.setTitle("\(data)", forState: UIControlState.Normal)
}
}
There have been some updates since Swift 4. This works for me:
self.button.setTitle("Button Title", for: UIControl.State.init(rawValue: 0))
Replace button with your IBOutlet name. You can also use a variable or array in place of the quoted text.
It's fairly simple ...
import UIKit
class ViewController: UIViewController {
#IBOutlet var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.setTitle("hello world", forState: UIControlState.Normal)
}
}
I believe if you set the state to normal, the value will propagate by default to other states so long as you haven't explicitly set a title for those states.
Said differently, if you set it for normal, it should also display this title when the button enters additional states
UIControlState.allZeros
UIControlState.Application
UIControlState.Disabled
UIControlState.Highlighted
UIControlState.Reserved
UIControlState.Selected
Lastly, here's Apple's documentation in case you have other questions.
Since your API call should be running on a background thread you need to dispatch your UI update back to the main thread like this:
DispatchQueue.main.async {
button.setTitle(“new value”, forState: .normal)
}
After setting the title, just a simple redraw of the button will do:
button.setNeedsDisplay();

Tap and Hold UIButton in Swift?

I am trying to get a UIButton to repeat the code over and over until the user releases the button. I have an up arrow in a game and when it is tapped, a space ship will go up until it is released. Here is the code for my button:
//at top of page
let upArrow = UIButton()
//in viewdidload()
let upArrowImage = UIImage(named: "upArrow") as UIImage?
upArrow.setImage(upArrowImage, forState: .Normal)
upArrow.frame = CGRectMake(10, 220, 90, 40)
upArrow.addTarget(self, action: "upArrowTouched:", forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(upArrow)
//outside of viewDidLoad()
func upArrowTouched(sender:UIButton!){
spaceship.position = CGPointMake(spaceship.position.x, spaceship.position.y + 3)
}
Any suggestions??
You need to implement your own solution for this, something along the lines
1- User touches down (UIControlEvent touchDown), you start a time that fires every x secs/millisecs
2- Timer will fire the action over and over
3- User touches up UICOntrolEvent touchUp, you cancel your timer
So you bind those 2 events to different functions, and start/kill your timers with appropriate actions
How that helps
Daniel

Swift Link Button to Controller

I have a programatically made button, which i would like to connect it to an action so that it goes straight to another view when I click it. Normally i would just control + drag. but i can't since it programatically made. How would i link this code to my "ViewController" so when i click it, the ViewController(log-in screen) Pops up.
The Code is here, and its from https://github.com/mamaral/Onboard
let thirdPage: OnboardingContentViewController = OnboardingContentViewController(title: "Seriously Though", body: "Kudos to the photographer.", image: UIImage(named:"yellow"), buttonText: "Let's Get Started"){ //Enter Action Here//
I'm not sure whether this part is necessary to help you, but i'll link it just in case
if (countElements(self.buttonText) != 0) {
var actionButton: UIButton = UIButton(frame: CGRectMake((CGRectGetMaxX(self.view.frame) / 2) - (contentWidth / 2), CGRectGetMaxY(self.view.frame) - kDefaultMainPageControlHeight - kDefaultActionButtonHeight - self.bottomPadding, contentWidth, kDefaultActionButtonHeight))
actionButton.titleLabel?.font = UIFont .systemFontOfSize(24)
actionButton.setTitle(self.buttonText, forState: .Normal)
actionButton.setTitleColor(self.buttonTextColor, forState: .Normal)
actionButton.addTarget(self, action: "handleButtonPressed", forControlEvents: .TouchUpInside)
self.view.addSubview(actionButton)
Going off of this line of code:
actionButton.addTarget(self, action: "handleButtonPressed", forControlEvents: .TouchUpInside)
If it isn't working, you probably forgot to add an actual function titled "handleButtonPressed"--something like this:
func handleButtonPressed() {
// Show the view that needs showing
}

Resources