Change a constraints constant using code - ios

I am creating this generic base code for all my views, It creates an ad bar that flows across all my pages. I have just included some code from the best answer to this Question and I cant work out why it doesn't work. I am trying to make it so if the adBanner doesn't load my labels stretch out and take up that space.
I apologise if this is obvious but I am new to this.
Here is my code
import Foundation
import UIKit
import iAd
class dayPicker: UIViewController , ADBannerViewDelegate{
var UIiAd: ADBannerView = ADBannerView()
var SH = UIScreen.mainScreen().bounds.height
var AH = CGFloat()
#IBOutlet var constOne: NSLayoutConstraint!
#IBOutlet var constTwo: NSLayoutConstraint!
func appdelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 1
AH = 50
UIView.commitAnimations()
self.constOne.constant == 58
self.constTwo.constant == 58
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 0
AH = 0
UIView.commitAnimations()
self.constOne.constant == 8
self.constTwo.constant == 8
}
override func viewWillAppear(animated: Bool) {
UIiAd.delegate = self
UIiAd = self.appdelegate().UIiAd
UIiAd.frame = CGRectMake(0, SH - AH , 0, 0)
self.view.addSubview(UIiAd)
}
}

You are giving == instead of = while assigning.
import Foundation
import UIKit
import iAd
class dayPicker: UIViewController , ADBannerViewDelegate{
var UIiAd: ADBannerView = ADBannerView()
var SH = UIScreen.mainScreen().bounds.height
var AH = CGFloat()
#IBOutlet var constOne: NSLayoutConstraint!
#IBOutlet var constTwo: NSLayoutConstraint!
func appdelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 1
AH = 50
UIView.commitAnimations()
self.constOne.constant = 58
self.constTwo.constant = 58
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 0
AH = 0
UIView.commitAnimations()
self.constOne.constant = 8
self.constTwo.constant = 8
}
override func viewWillAppear(animated: Bool) {
UIiAd.delegate = self
UIiAd = self.appdelegate().UIiAd
UIiAd.frame = CGRectMake(0, SH - AH , 0, 0)
self.view.addSubview(UIiAd)
}
}

Related

I can't use different colors or rubber in PencilKit

Why can't I use other pencils or colors as expected in this app? It only draws a black color. This is my code:
import UIKit
import PencilKit
import PhotosUI
​
class ViewController: UIViewController, PKCanvasViewDelegate, PKToolPickerObserver {
​
#IBOutlet weak var pencilButton: UIBarButtonItem!
#IBOutlet weak var canvasView: PKCanvasView!
let canvasWidth: CGFloat = 768
let canvasOverScrollHeight: CGFloat = 500
let drawing = PKDrawing()
​
override func viewDidLoad() {
super.viewDidLoad()
canvasView.drawing = drawing
canvasView.delegate = self
canvasView.alwaysBounceVertical = true
canvasView.drawingPolicy = .anyInput
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
​
let toolPicker = PKToolPicker()
toolPicker.setVisible(true, forFirstResponder: canvasView)
toolPicker.addObserver(canvasView)
canvasView.becomeFirstResponder()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let canvasScale = canvasView.bounds.width / canvasWidth
canvasView.minimumZoomScale = canvasScale
canvasView.maximumZoomScale = canvasScale
canvasView.zoomScale = canvasScale
updateContentSizeForDrawing()
canvasView.contentOffset = CGPoint(x: 0, y: -canvasView.adjustedContentInset.top)
}
override var prefersHomeIndicatorAutoHidden: Bool{
return true
}
#IBAction func fingerOrPencil (_ sender: Any) {
canvasView.allowsFingerDrawing.toggle()
pencilButton.title = canvasView.allowsFingerDrawing ? "Finger" : "Pencil"
}
#IBAction func saveToCameraRoll(_ sender: Any) {
UIGraphicsBeginImageContextWithOptions(canvasView.bounds.size, false, UIScreen.main.scale)
canvasView.drawHierarchy(in: canvasView.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if image != nil {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image!)
}, completionHandler: {success, error in
})
}
}
func updateContentSizeForDrawing() {
let drawing = canvasView.drawing
let contentHeight: CGFloat
if !drawing.bounds.isNull {
contentHeight = max(canvasView.bounds.height, (drawing.bounds.maxY + self.canvasOverScrollHeight) * canvasView.zoomScale)
} else {
contentHeight = canvasView.bounds.height
}
canvasView.contentSize = CGSize(width: canvasWidth * canvasView.zoomScale, height: contentHeight)
}
// Delegate Methods
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
updateContentSizeForDrawing()
}
func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) {
}
func canvasViewDidFinishRendering(_ canvasView: PKCanvasView) {
}
func canvasViewDidBeginUsingTool(_ canvasView: PKCanvasView) {
}
}
These are the outputs in the console:
2023-01-04 18:34:04.429420+0300 Drawing[45460:449613] [Assert] UINavigationBar decoded as unlocked for UINavigationController, or navigationBar delegate set up incorrectly. Inconsistent configuration may cause problems. navigationController=<UINavigationController: 0x123024000>, navigationBar=<UINavigationBar: 0x12140a0a0; frame = (0 47; 0 50); opaque = NO; autoresize = W; layer = <CALayer: 0x6000030afae0>> delegate=0x123024000
2023-01-04 18:34:04.468831+0300 Drawing[45460:449613] Metal API Validation Enabled
2023-01-04 18:34:04.705019+0300 Drawing[45460:449613] [ToolPicker] Missing defaults dictionary to restore state for: PKPaletteNamedDefaults
2023-01-04 18:35:00.196200+0300 Drawing[45460:449613] Keyboard cannot present view controllers (attempted to present <UIColorPickerViewController: 0x121846e00>)
toolPicket released when out of method scope.
You should have a instance of toolPicker in ViewController.
class ViewController: UIViewController {
let toolPicker = PKToolPicker()
...
}
i solved my problem by changing
toolPicker.addObserver(self)
into
toolPicker.addObserver(canvasView)
and adding the toolPicker at the top as #noppefoxwolf suggested

app only updates when i close and re-open it

I am trying to build an IOS app where the user puts options in to a tableview, then the options appear and the spinning frame spins and stops at a random point.
I have put all the necessary code in ViewWillAppear but for some reason the app doesn't update with the user defaults, only when i close the app and re-open it.
It did actually work at one point but then stopped and i have no idea how to fix it. I am using TTFortuneWheel Pod.
ImageOne
ImageTwo
I will link my GitHub in case anyone wants to have a look at the full code.
https://github.com/jamesnjones/Just.Decide
below is the code for the main screen
import UIKit
import TTFortuneWheel
import AVFoundation
class ViewController: UIViewController, UINavigationControllerDelegate {
#IBOutlet weak var spinningWheel: TTFortuneWheel!
#IBOutlet weak var ResultsLabel: UILabel!
let transition = SlideInTransition()
var slices : [CarnivalWheel] = []
var result: String?
var player: AVAudioPlayer!
var soundIsOn = true
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.delegate = self
spinningWheel.initialDrawingOffset = 270.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("check")
slices = getSlices()
spinningWheel.slices = slices
spinningWheel.equalSlices = true
spinningWheel.frameStroke.width = 0
spinningWheel.titleRotation = CGFloat.pi
spinningWheel.slices.enumerated().forEach { (pair) in
let slice = pair.element as! CarnivalWheel
let offset = pair.offset
switch offset % 6 {
case 0: slice.style = .blue
case 1: slice.style = .green
case 2: slice.style = .grey
case 3: slice.style = .orange
case 4: slice.style = .purple
default: slice.style = .yellow
}
}
}
private func getSlices() -> [CarnivalWheel] {
PersistenceManager.retrieveSlices { [weak self] result in
guard let self = self else {return}
switch result {
case .success(let slices):
if slices.isEmpty {
print("this is where i will add an alert or sumin")
}else {
self.slices = slices
DispatchQueue.main.async {
self.reloadInputViews()
}
}
case .failure(let error):
print("Edit VC Errror ")
}
}
return slices
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
true
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
true
}
#IBAction func rotateButton(_ sender: UIButton) {
if soundIsOn {
playSound(soundName: "spinning")
ResultsLabel.text = ""
let randomNumber = Int.random(in: 0...slices.count - 1)
spinningWheel.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
self.spinningWheel.startAnimating(fininshIndex: randomNumber) { (finished) in
self.ResultsLabel.text = self.spinningWheel.slices[randomNumber].title
}
}
} else {
ResultsLabel.text = ""
let randomNumber = Int.random(in: 0...slices.count - 1)
spinningWheel.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
self.spinningWheel.startAnimating(fininshIndex: randomNumber) { (finished) in
self.ResultsLabel.text = self.spinningWheel.slices[randomNumber].title
}
}
}
}
Rather than putting it inside of your viewWillAppear put it inside of the viewDidAppear:
override func viewDidAppear(_ animated: Bool) {
<#code#>
}

Shared iAd banner

I am making the iAds in my app to be loaded in the app delegate. It loads fine however in the view controllers, it will not show.
My code in the app delegate to declare the ad is
var UIiAd: ADBannerView = ADBannerView()
My code in the view controller is
class HelpViewController: UIViewController, ADBannerViewDelegate {
//MARK: - Properties
var UIiAd: ADBannerView = ADBannerView()
//MARK: - did something
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
//super.viewWillAppear(animated)
let ScreenHeight = UIScreen.mainScreen().bounds.height
UIiAd.delegate = self
UIiAd = self.appDelegate().UIiAd
UIiAd.frame = CGRectMake(0, ScreenHeight - 50, 0, 0)
UIiAd.hidden = true
self.view.addSubview(UIiAd)
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - iAd
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.hidden = false
UIView.commitAnimations()
print("Did load ad")
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0)
UIiAd.hidden = true
UIView.commitAnimations()
print("Did fail to receive ad with error \(error)")
}
//MARK: - Functions
func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
}
What seems to be the problem is, bannerViewDidLoadAd doesn't ever get called. How would I unhide the banner if it loads?
I have actually fixed this. What you need to do in the app delegate is
class AppDelegate: UIResponder, UIApplicationDelegate, ADBannerViewDelegate
Then you want to make a bool that changes if the ad is loaded
Then you want to add the function func bannerViewDidLoadAd(banner: ADBannerView!) {
adLoaded = true
}
This will change the value when the ad is loaded
Then in your view controller you want to do
override func viewWillAppear(animated: Bool) {
//super.viewWillAppear(animated)
let ScreenHeight = UIScreen.mainScreen().bounds.height
UIiAd.delegate = self
UIiAd = self.appDelegate().UIiAd
UIiAd.frame = CGRectMake(0, ScreenHeight - 50, 0, 0)
canDisplayBannerAds = true
if appDelegate().adLoaded == true {
self.view.addSubview(UIiAd)
}
}
This will add the ad to your view controller will not if the ad is not loaded

How to get a BannerAd at the bottom of the screen. Xcode 7.0.1

Hey This is the code I used for Xcode 6.4 but when I go to Xcode 7 there's an error. So at first I just deleted the ConstantsH and V. That got rid of the errors but then I look at the app and the banner is no longer at the bottom of the scree now its at the top. How do I change that back in Xcode 7? Thanks in advance.
Code:
class GameViewController: UIViewController, ADBannerViewDelegate{
var bannerAd = ADBannerView(adType: ADAdType.Banner)
override func viewDidLoad() {
super.viewDidLoad()
bannerAd.delegate = self
self.view.addSubview(bannerAd)
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("|[bannerAd]|", options: nil, metrics: nil, views: ["bannerAd":bannerAd])
let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerAd(50)]|", options: nil, metrics: nil, views: ["bannerAd":bannerAd])
self.view.addConstraints(constraintsH)
self.view.addConstraints(constraintsV)
Full File Below:-----------------
import StoreKit
import SpriteKit
import GameKit
import iAd
class GameViewController: UIViewController, ADBannerViewDelegate{
var bannerAd = ADBannerView(adType: ADAdType.Banner)
override func viewDidLoad() {
super.viewDidLoad()
bannerAd.delegate = self
self.view.addSubview(bannerAd)
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("|[bannerAd]|", options: nil, metrics: nil, views: ["bannerAd":bannerAd])
let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerAd(50)]|", options: nil, metrics: nil, views: ["bannerAd":bannerAd])
self.view.addConstraints(constraintsH)
self.view.addConstraints(constraintsV)
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
{
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
let localPlayer = GKLocalPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if (viewController != nil) {
let vc: UIViewController = self.view!.window!.rootViewController!
vc.presentViewController(viewController!, animated: true, completion: nil)
}
else {
print((GKLocalPlayer.localPlayer().authenticated))
}
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let scene = GameScene()
let sKView = self.view! as! SKView
sKView.ignoresSiblingOrder = true
scene.size = sKView.bounds.size
scene.scaleMode = .AspectFill
let reveal = SKTransition.fadeWithDuration(0.45)
sKView.presentScene(scene, transition: reveal)
}
override func shouldAutorotate() -> Bool {
if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
return false;
}
else {
return true;
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
NSLog("bannerViewWillLoadAd")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
NSLog("bannerViewDidLoadAd")
self.bannerAd.hidden = false//now show banner as ad is loaded
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
NSLog("bannerViewDidLoadAd")
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
NSLog("bannerViewActionShouldBegin")
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("bannerView")
self.bannerAd.hidden = true
}
}
This is how you do it
bannerAd.center = CGPoint(x: bannerAd.center.x, y: view.bounds.size.height - bannerAd.frame.size.height * 0.05)

Running a function (pause menu) when iAd is clicked SpriteKit Swift

I have implemented iAds in my SpriteKit / Swift game. I cannot find out how to run a function in GameScene when the user clicks on the ad (I have a function that brings up a pause menu) and not just pause the scene. How do I accomplish this? Thanks.
EDIT: This is my GameViewController.
import UIKit
import SpriteKit
import iAd
class GameViewController: UIViewController, ADBannerViewDelegate {
var SH = UIScreen.mainScreen().bounds.height
let transition = SKTransition.fadeWithDuration(1)
var UIiAd: ADBannerView = ADBannerView()
override func viewWillAppear(animated: Bool) {
/* var BV = UIiAd.bounds.height
UIiAd.delegate = self
UIiAd.frame = CGRectMake(0, SH + BV, 0, 0)
self.view.addSubview(UIiAd) */
UIiAd.setTranslatesAutoresizingMaskIntoConstraints(false)
UIiAd.delegate = self
self.view.addSubview(UIiAd)
let viewsDictionary = ["bannerView":UIiAd]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary))
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1) // Time it takes the animation to complete
UIiAd.alpha = 1 // Fade in the animation
UIView.commitAnimations()
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 0
UIView.commitAnimations()
}
func showBannerAd() {
UIiAd.hidden = false
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(10) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH - BV, 2048, 0) // End position of the animation
UIView.commitAnimations()
}
func hideBannerAd() {
UIiAd.hidden = true
var BV = UIiAd.bounds.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1) // Time it takes the animation to complete
UIiAd.frame = CGRectMake(0, SH + BV, 0, 0) // End position of the animation
UIView.commitAnimations()
}
override func viewDidLoad() {
super.viewDidLoad()
self.UIiAd.hidden = true
self.UIiAd.alpha = 0
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hideBannerAd", name: "hideadsID", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showBannerAd", name: "showadsID", object: nil)
let scene = MainMenu(size: CGSize(width: 2048, height: 1356))
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
Then in the GameScene I import iAd, add ADBannerViewDelegate, then add this code
var iAdBanner: ADBannerView = ADBannerView()
func showAds(){
NSNotificationCenter.defaultCenter().postNotificationName("showadsID", object: nil)
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
iAdBanner.delegate = self
println("Clicked")
paused = true
return true
}
Try this function for banner iAd:
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
println("Clicked")
// If you want to pause game scene:
let skView: SKView = self.view as! SKView
skView.scene.paused = true
return true
}
and also:
func bannerViewActionDidFinish(banner: ADBannerView!) {
println("Closed")
// If you want to continue game scene:
let skView: SKView = self.view as! SKView
skView.scene.paused = false
}

Resources