my app Dotcha! is now on the app store and I am trying to make an update in xcode. In my update I fix some minor things and a few major things. My problem is that I screwed around with the Interstitial ads that I had working and now they don't seem to work anymore. Here is my code.
func Close(sender:UIButton){
closeButton.removeFromSuperview()
InterAdView.removeFromSuperview()
}
func loadAd() {
println("load ad")
InterAd = ADInterstitialAd()
InterAd.delegate = self
}
func interstitiallAdDidLoad(interstitialAd: ADInterstitialAd!) {
println("ad did load")
InterAdView = UIView()
InterAdView.frame = self.view.bounds
view.addSubview(InterAdView)
InterAd.presentInView(InterAdView)
UIViewController.prepareInterstitialAds()
InterAdView.addSubview(closeButton)
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
println("Ad Unloaded")
InterAdView.removeFromSuperview()
closeButton.removeFromSuperview()
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
println("failed to receive")
println(error.localizedDescription)
closeButton.removeFromSuperview()
InterAdView.removeFromSuperview()
}
func RandomInterstitialAd(){
var RandomAd = arc4random() % 6
switch(RandomAd){
case 0:
break
case 1:
loadAd()
break
case 2:
break
case 3:
loadAd()
break
case 4:
break
case 5:
break
default:
break
}
Close button code in viewDidLoad:
closeButton.frame = CGRectMake(20, 20, 30, 30)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("X", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: "Close:", forControlEvents: UIControlEvents.TouchDown)
}
var InterAd = ADInterstitialAd()
var InterAdView: UIView = UIView()
var closeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
I call the RandomInterstitialAd() function when the a button is pressed. The console prints in load Ad, but the ad never loads. Please help.
Related
[Type 'MapViewController' has no member 'mapTypeChanged'][2]
in line:
action: #selector(MapViewController.mapTypeChanged(_:)),
There is a method mapTypeChanged at the bottom of the code, so I'm unsure why the error says there is no member mapTypeChanged ? I'm guessing mapTypeChanged needs to be declared as a variable (global?)
import UIKit
import MapKit
class MapViewController: UIViewController {
var mapView: MKMapView!
override func loadView() {
mapView = MKMapView()
view = mapView
let segmentedControl
= UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
segmentedControl.backgroundColor
= UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self,
action: #selector(MapViewController.mapTypeChanged(_:)),
for: .valueChanged)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let topConstraint
= segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8)
let margins = view.layoutMarginsGuide
let leadingConstraint =
segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
let trailingConstraint =
segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
func mapTypeChanged(_segControl: UISegmentedControl) {
switch _segControl.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
default:
break
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("MapViewController Loaded its view.")
}
}
#selector(MapViewController.mapTypeChanged(_:))
means "call mapTypeChanged method".
So You need to implement mapTypeChanged.
func mapTypeChanged(_ sender: UISegmentedControl) {
print(sender.selectedSegmentIndex)
}
For Xcode 9.3.1 the function mapTypeChanged must be outside override func loadView() and preceded by #objc:
#objc func mapTypeChanged(_ segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
...
}
}
The #objc attribute makes your Swift API available in Objective-C and the Objective-C runtime.
I'm trying to have a custom UIButton become hidden once it's pressed a certain number of times...but I'm at a loss.
Having exhausted my limited knowledge and consulting the Apple's documentation as well as the internet for the better part of 3 hours, I've finally made my way here. I've been learning Swift for a short while now and am making an effort to become more familiar with it. This is my first object-oriented language and it's testing me to say the least. Any help with this more likely than not ridiculously simple problem is very much appreciated.
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var buttonMessageDisplay: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
buttonPressed()
}
var tapcount = 0
let buttonMessage : [String] = [/* long array of strings */]
func buttonPressed() {
let button = UIButton(type:.Custom) as UIButton
button.frame = CGRectMake(0, 0, 100, 100)
button.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
button.backgroundColor = UIColor.redColor()
button.layer.borderColor = UIColor.blackColor().CGColor
button.layer.borderWidth = 3
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.setTitle("", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed", forControlEvents: .TouchUpInside)
view.addSubview(button)
switch tapcount {
case 19...23:
//Hides the button
button.hidden = true
buttonMessageDisplay.text = buttonMessage[tapcount]
case 24...31:
//Unhides the button
button.hidden = false
buttonMessageDisplay.text = buttonMessage[tapcount]
default:
buttonMessageDisplay.text = buttonMessage[tapcount]
}
print("Tap Count: \(tapcount)")
++tapcount
}
Updated with Gesture Recognizer:
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var buttonMessageDisplay: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
buttonMessageDisplay.text = ""
let button = UIButton(type:.Custom) as UIButton
button.frame = CGRectMake(0, 0, 100, 100)
button.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
button.backgroundColor = UIColor.redColor()
button.layer.borderColor = UIColor.blackColor().CGColor
button.layer.borderWidth = 3
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.setTitle("", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
var tapcount : Int = 0
let buttonMessage : [String] = [/* array of strings */]
#IBAction func userTap(sender: UITapGestureRecognizer) {
print("Tap Received")
if case 19...23 = tapcount {
buttonPressed()
}
}
func buttonPressed() {
switch tapcount {
case 0...18:
buttonMessageDisplay.text = buttonMessage[tapcount]
case 19...23:
//Hides the button
button.hidden = true
buttonMessageDisplay.text = buttonMessage[tapcount]
case 24...32:
//Unhides the button
button.hidden = false
buttonMessageDisplay.text = buttonMessage[tapcount]
case 33...100:
buttonMessageDisplay.text = buttonMessage[tapcount]
default:
print("There are no more messages or an error has been encountered")
}
print("Tap Count: \(tapcount)")
++tapcount
}
}
Your code makes no sense. As #formal says in his answer, you're creating a new button on every tap, which is wrong.
You want to define your button in your Storyboard.
Then you want an IBAction method, which takes the button as a parameter:
#IBAction func buttonPressed(sender: UIButton)
{
++tapcount
if tapcount < 19
{
sender.hidden = true
}
}
Note that if the button you're hiding is the same one the user is tapping, once it is hidden, you're done. The user can't tap a hidden button, so there's no way to un-hide it. (And thus no point in your switch statement)
Your main issue is that you are creating a new button every time you call button pressed. Create an #IBOutlet for your button and just set its hidden property in butPressed (which can be set as an action of the button).
Something like:
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
#IBOutlet weak var buttonMessageDisplay: UILabel!
var tapcount = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func butPressed(sender: AnyObject) {
switch tapcount {
case 19...23:
//Hides the button
button.hidden = true
case 24...31:
//Unhides the button
button.hidden = false
default: break
}
print("Tap Count: \(tapcount)")
buttonMessageDisplay.text = "Tap: \(tapcount)"
++tapcount
}
}
The method buttonPressed() creates a new button each time it is called. You should define button as a property similar to buttonMessageDisplay and place the code to initialise it within viewDidLoad().
You should give space between range in case condition:
For example:
(IBAction)buttonTapped:(id)sender {
self.count++;
switch (self.count) {
case 5 ... 23 :
self.button.titleLabel.text = #"disable";
self.button.hidden = true;
break;
default:
break;
}
}
I'm trying to implement interstitial ads with iAd into my spriteKit game. My code is as follows:
class ViewController: UIViewController, ADInterstitialAdDelegate {
var interAd = ADInterstitialAd()
var interAdView: UIView!
var closeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
override func viewDidAppear(animated: Bool) {
closeButton.frame = CGRectMake(10, 10, 20, 20)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("x", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: "close:", forControlEvents: UIControlEvents.TouchDown)
}
func close(sender: UIButton) {
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
func loadAd() {
println("load ad")
interAd = ADInterstitialAd()
interAd.delegate = self
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
println("ad did load")
interAdView = UIView()
interAdView.frame = self.view!.frame
view!.addSubview(interAdView)
interAd.presentInView(interAdView)
UIViewController.prepareInterstitialAds()
interAdView.addSubview(closeButton)
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
println("failed to receive")
println(error.localizedDescription)
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
This code delivers me more problems than it does results. Unfortunately I am a beginner at implementing any sort of ads into an app and I don't know how I can change any of this in my favour.
One issue I get is that output traces ad did load (as you can see thats supposed to be traced once the ad is presented) however when ad did load is traced no ad is presented. I wait for at least 3 minutes but nothing happens.
Another issue I have is this WARNING: More than 10 instances of ADBannerView or ADInterstitialView currently exist. This is a misuse of the iAd API, and ad performance will suffer as a result. This message is printed only once., but this is printed after the function to load the ad is called once or twice.
The "go button" is not working as it should. When clicked it should hide the subviews. Here's the ViewController. I tried placing the final function in various places.
class timeViewController: UIViewController {
var score = 0
var buttonState: Int = 0;
var gameOver = UIView()
#IBAction func start(sender: AnyObject) {
if(displayTime.text != stoptimer.text){
var gameOver = UIView(frame: CGRectMake(0, 0, 0, 0))
gameOver.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
//gameOver.opaque = false
self.view.addSubview(gameOver)
UIView.animateWithDuration(0, animations:{
gameOver.frame.size = CGSizeMake(667, 667)
})
let gobutton = UIButton()
let image = "button.png"
gobutton.setImage(UIImage(named: image), forState: .Normal)
gobutton.frame = CGRectMake(135, 300, 95, 95)
gobutton.addTarget(self, action: "pressed:" , forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(gobutton)
func pressed(sender: UIButton!){
gameOver.removeFromSuperview()
}
}
}
For removing your "GaneOver" view change to this code:
gameOver.removeFromSuperview()
And I hope you are writing "func pressed" outside of viewDidLoad or viewWillAppear
You will have to make gameOver a global variable by declaring it outside function and then do what you did like this:
class myClass {
var gameOver = UIView()
func myFunction() {/*edit everything including gameOverView's properties*/}
func pressed(sender: UIButton!) {
gameOver.removeFromSuperview()
}
}
Also make sure to write functions outside other functions like viewDidLoad but inside your class as it looks like you created that function inside another one. However you can call a function from within another one using something like myFunction() as separate line as is.
Hope that helps :)
You're re-declaring gameOver inside the if statement. Just remove var. Check this code out:
class ViewController: UIViewController {
var gameOver: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func start(sender: AnyObject) {
if(displayTime.text != stoptimer.text){
gameOver = UIView(frame: CGRectMake(0, 0, 0, 0))
gameOver.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
//gameOver.opaque = false
self.view.addSubview(gameOver)
UIView.animateWithDuration(0, animations:{
self.gameOver.frame.size = CGSizeMake(667, 667)
})
let gobutton = UIButton()
let image = "button.png"
gobutton.setImage(UIImage(named: image), forState: .Normal)
gobutton.frame = CGRectMake(135, 300, 95, 95)
gobutton.addTarget(self, action: "pressed:" , forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(gobutton)
}
}
func pressed(sender: UIButton!){
self.gameOver.removeFromSuperview()
}
}
I want to launch a modal view with a long press, and then dismiss the modal view when the long press is cancelled. How do I do this?
I tried passing the longPressRecognizer to the modal view and
setting it as a delegate, but that didn't work.
I tried something simpler- detecting a touchesEnded, which would mean in the modal view a touch ended, but that doesn't fire either.
Is there a way to tell the modal view a gesture has started; I want you to recognize the end/cancellation of this gesture or a touch?
ViewController.swift
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var buttonView:UIView!
var longPressRecognizer:UILongPressGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.longPressRecognizer.delegate = self
self.view.addGestureRecognizer(self.longPressRecognizer)
// Add a button
buttonView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100))
buttonView.userInteractionEnabled = true;
buttonView.backgroundColor = UIColor.grayColor()
self.view.addSubview(buttonView)
}
func longPressed(recognizer: UILongPressGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self.view)
if let pressedView = self.view.hitTest(point, withEvent: nil) {
if pressedView == self.buttonView {
switch recognizer.state {
case .Began:
NSLog("long pressed - Began")
var mediaViewController = MediaViewController()
self.presentViewController(mediaViewController, animated: false, completion: nil)
case .Cancelled:
NSLog("long pressed - Cancelled")
case .Ended:
NSLog("long pressed - Ended")
default:
break
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
MediaViewController.swift
import UIKit
class MediaViewController: UIViewController, UIGestureRecognizerDelegate {
var longPressRecognizer:UILongPressGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGrayColor()
self.longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.longPressRecognizer.delegate = self
self.view.addGestureRecognizer(self.longPressRecognizer)
}
func longPressed(recognizer: UILongPressGestureRecognizer) {
switch recognizer.state {
case .Began:
NSLog("long pressed - Began")
case .Cancelled:
NSLog("long pressed - Cancelled")
case .Ended:
NSLog("long pressed - Ended")
self.dismissViewControllerAnimated(false, completion: nil)
default:
break
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
NSLog("touches began")
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
NSLog("touches ended")
}
}
Hmmm, this appears to work and handle a tap gesture simultaneously with the long press. Not bad!
ViewController.swift
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var buttonView:UIView!
var longPressRecognizer:UILongPressGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Add a button
buttonView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100))
buttonView.userInteractionEnabled = true;
buttonView.backgroundColor = UIColor.grayColor()
self.view.addSubview(buttonView)
}
override func viewDidAppear(animated: Bool) {
if let recognizer = self.longPressRecognizer {
// Reuse existing recognizer
self.longPressRecognizer = recognizer
recognizer.removeTarget(nil, action: nil)
recognizer.addTarget(self, action: "longPressed:")
recognizer.delegate = self
self.view.addGestureRecognizer(recognizer)
} else {
// Create a new new recognizer
self.longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.longPressRecognizer!.delegate = self
self.view.addGestureRecognizer(self.longPressRecognizer!)
}
}
override func viewDidDisappear(animated: Bool) {
// Remove the recognizer
if let recognizer = self.longPressRecognizer {
self.view.removeGestureRecognizer(recognizer)
}
}
func longPressed(recognizer: UILongPressGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self.view)
if let pressedView = self.view.hitTest(point, withEvent: nil) {
if pressedView == self.buttonView {
switch recognizer.state {
case .Began:
NSLog("ViewController: long pressed - Began")
var mediaViewController = MediaViewController()
mediaViewController.addRecognizer(recognizer)
self.presentViewController(mediaViewController, animated: false, completion: nil)
case .Cancelled:
NSLog("ViewController: long pressed - Cancelled")
case .Ended:
NSLog("ViewController: long pressed - Ended")
case .Changed:
NSLog("ViewController: long pressed - Changed")
default:
break
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
MediaViewController.swift
class MediaViewController: UIViewController, UIGestureRecognizerDelegate {
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGrayColor()
self.tapRecognizer = UITapGestureRecognizer(target: self, action: "tap:")
self.tapRecognizer.cancelsTouchesInView = false
self.tapRecognizer.delegate = self
self.view.addGestureRecognizer(self.tapRecognizer)
self.longPressRecognizer.removeTarget(nil, action: nil)
self.longPressRecognizer.addTarget(self, action: "longPressed:")
self.longPressRecognizer.delegate = self
self.view.addGestureRecognizer(self.longPressRecognizer)
}
override func viewWillDisappear(animated: Bool) {
// Remove gesture recognizers
self.view.removeGestureRecognizer(self.longPressRecognizer)
self.longPressRecognizer.delegate = nil
self.view.removeGestureRecognizer(self.tapRecognizer)
self.tapRecognizer.delegate = nil
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true;
}
func longPressed(recognizer: UILongPressGestureRecognizer) {
switch recognizer.state {
case .Began:
NSLog("MediaViewController: long pressed - Began")
case .Cancelled:
NSLog("MediaViewController: long pressed - Cancelled")
case .Ended:
NSLog("MediaViewController: long pressed - Ended")
self.dismissViewControllerAnimated(false, completion: nil)
case .Changed:
NSLog("MediaViewController: long pressed - Changed")
default:
break
}
}
func tap(recongizer: UITapGestureRecognizer) {
if (self.view.backgroundColor == UIColor.lightGrayColor()) {
self.view.backgroundColor = UIColor.greenColor()
} else {
self.view.backgroundColor = UIColor.lightGrayColor()
}
}
func addRecognizer(recognizer: UILongPressGestureRecognizer) {
self.longPressRecognizer = recognizer
}
}