Add Target for UIButton Not Called - ios

I have two view controllers that I am currently working with. In my CathyTaskLogMessageViewController, I have this code:
func defaultPictureButtonTapped(sender: UIButton) {
let imageViewerViewController = ImageViewerViewController()
imageViewerViewController.image = self.defaultPictureButton.imageView!.image
imageViewerViewController.cancelButtonImage = UIImage(named: "cancelButtonImage")
imageViewerViewController.centerPictureFromPoint(self.defaultPictureButton.frame.origin, ofSize: self.defaultPictureButton.frame.size, withCornerRadius: self.defaultPictureButton.layer.cornerRadius)
self.view.addSubview(imageViewerViewController.view)
}
And in my ImageViewerViewController, I have this code:
var image: UIImage!
var imageView: UIImageView!
var scrollView: UIScrollView!
var disableSavingImage: Bool!
var pan: UIPanGestureRecognizer!
var cancelButton: UIButton!
var cancelButtonImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0)
setCancelButton()
}
func setCancelButton() {
self.cancelButton = UIButton(type: UIButtonType.RoundedRect)
self.cancelButton.addTarget(self, action: "cancelButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
self.cancelButton.setImage(cancelButtonImage, forState: UIControlState.Normal)
self.cancelButton.tintColor = UIColor.whiteColor()
self.cancelButton.frame = CGRectMake(self.view.frame.size.width - (self.cancelButtonImage.size.width * 2) - 18, 18, self.cancelButtonImage.size.width * 2, self.cancelButtonImage.size.height * 2)
self.view.addSubview(self.cancelButton)
}
func cancelButtonTapped(sender: UIButton) {
print("cancelButtonTapped")
}
func centerPictureFromPoint(point: CGPoint, ofSize size: CGSize, withCornerRadius radius: CGFloat) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.backgroundColor = UIColor(colorLiteralRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}) { (finished: Bool) -> Void in
}
}
Now, when I tap the cancel button, it should print "cancelButtonTapped" in the console. However, there is not output from the console.
I think the problem has to do with the button being in a different subview perhaps? I'm not exactly sure. Anybody have a solution to this problem?
Also, when the cancel button loads, it loads from the left and moves to the right. Is there a way that the button just appears on the top right hand corner?
Thank you in advance for your help.

change background color, so you can identify the problem.
put this line in viewDidLayoutSubviews() this method so it loads from the left and moves to the right can solve
code:
override func viewDidLayoutSubviews() {
self.cancelButton.frame = CGRectMake(self.view.frame.size.width - (self.cancelButtonImage.size.width * 2) - 18, 18, self.cancelButtonImage.size.width * 2, self.cancelButtonImage.size.height * 2)
}

Related

Resize UISwitch in Swift 4

I would like to change the default size of the UISwitch in Swift 4.
I have looked at various options but they all relate to v3 and do not work.
Please can someone suggest an example that does so programmatically in Swift 4?
Thank you,
Edit:
I have tried the following examples:
switchTest.transform = CGAffineTransformMakeScale(0.75, 0.75)
switchTest.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
UISwitch *switchTest = [UISwitch new];
switchTest.transform = CGAffineTransformMakeScale(0.75, 0.75);
The error message that I received is always the same and says this:
Expected declaration
Swift 4 Code
Method 1
Drag UISwitch Storyboard. Make an outlet of your UISwitch and replace ViewDidLoad method by this code.
#IBOutlet weak var switchDemo: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchDemo.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
}
Method 2
Make UISwitch through programmatically.
class ViewController: UIViewController {
let switchSwift4 = UISwitch(frame:CGRect(x: 150, y: 300, width: 0, height: 0))
override func viewDidLoad() {
super.viewDidLoad()
self.switchSwift4.isOn = true
switchSwift4.setOn(true, animated: false)
switchSwift4.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
switchSwift4.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
self.view!.addSubview(switchSwift4)
}
#objc func switchValueDidChange(_ sender: UISwitch) {
if switchSwift4.isOn == true {
print("On")
}
else {
print("Off")
}
}
}

Starting an action when View Controller Loads

How do I start an action when the view controller loads on screen?
I've managed to do the function I want with an #IBAction but I don't want a button press for the action to happen, I want it to start the action when the page loads
any thoughts?
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
#IBAction func Animate(sender: AnyObject) {
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
Use :-
Basic idea here is that whenever your view will load corresponding class will look up to viewWillAppear(animated: Bool) function and if it's present in the code it will execute all the code in it.The moment that particular view is about to appear on your UI, your code block in viewWillAppear(animated: Bool) will get called.
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
}
override func viewWillAppear(animated :Bool) {
super.viewWillAppear(animated)
progressActn()
//Setting up your progress layer
animateActn()
//Animating that progress layer
}
#IBAction func Animate(sender: AnyObject) {
animateActn()
}
func animateActn(){
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
}
}
func progressActn(){
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
}

Swift Ints and some Doubles working but not all Doubles

What I am trying to do is increase the rate that the method spawnEnemy() is called on, and it works well using the starred numbers as Ints, but I felt like it goes by way too quickly so I thought of using Doubles and using the decimal point. However, if I go into the tenths spot of subtracting an amount from spawnRate in
self.spawnRate=spawnRate - 1.0 (I use anything but 0) spawnEnemy() will only be called on once in the simulator then nothing happens. Any advice or suggestions would be great. Thank you!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
var tickCount=0.0 // **
var spawnRate=15.0 // Spawn every 15 seconds to start with..... **
var spawnTimer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
self.tickCount=self.spawnRate
self.spawnTimer=NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
}
func tick() {
if (--tickCount == 0) { // **
self.spawnEnemy()
self.spawnRate=spawnRate - 0.5 // Change this to determine how quickly the spawn rate increases..... **
self.tickCount=self.spawnRate
}
}
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(568-arc4random()%390))
return randomPoint
}
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIButton = UIButton(frame: CGRect(x: 160, y: 160, width: 100, height: 100))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
if sender.frame.height < 50 || sender.frame.width < 50 {
sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
sender.backgroundColor = randomColor()
sender.center = randomPoint()
return
}
while sender.backgroundColor != UIColor.blackColor() {
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
sender.backgroundColor = UIColor.blackColor()
}
}
}
I think what's happening is you're trying to test a double with the equality operator. The problem is that there's always a bit of complexity in how doubles are stored that makes it very difficult to compare them with equality. Instead you need to do something like this:
if (--tickCount <= 0) {
That way you catch it going negative for sure, otherwise it can go right past 0 and continue to count down.

Spawning UIView every second at random CGPoint in Swift

I am trying to "spawn" a UIView with a random UIColor as its background at a random CGPoint. I am using the code below which compiles fine with no bugs or anything but when it runs in the simulator I click start(the button on the first ViewController) but then go to ViewTwo but nothing happens(no "enemies" are spawned). Thank you for any help.
import UIKit
var randomPoint: CGPoint = CGPoint(x: Int(arc4random()%1000), y: Int(arc4random()%1000))
class ViewController: UIViewController {
#IBOutlet weak var startGameButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class ViewTwo : UIViewController {
var timer = NSTimer()
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint
self.view.addSubview(enemy)
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Your randomPoint needs to be recalculated in spawnEnemy, and is generating a random x y from 0 to 1000 (and should also be a float) It will likely be off the screen.

Add Target for UIButton Not Being Called

I posted a similar post recently and I figured out what the problem is but I don't know how to fix the problem.
In my ImageViewerViewController, my cancelButtonTapped function is not being called. But I don't think the problem, necessarily, lies in this code. Here is the code:
var image: UIImage!
var imageView: UIImageView!
var scrollView: UIScrollView!
var disableSavingImage: Bool!
var pan: UIPanGestureRecognizer!
var cancelButton: UIButton!
var cancelButtonImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0)
setCancelButton()
}
func setCancelButton() {
self.cancelButton = UIButton(type: UIButtonType.RoundedRect)
self.cancelButton.addTarget(self, action: "cancelButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
self.cancelButton.setImage(cancelButtonImage, forState: UIControlState.Normal)
self.cancelButton.tintColor = UIColor.whiteColor()
self.cancelButton.frame = CGRectMake(self.view.frame.size.width - (self.cancelButtonImage.size.width * 2) - 18, 18, self.cancelButtonImage.size.width * 2, self.cancelButtonImage.size.height * 2)
self.view.addSubview(self.cancelButton)
}
func cancelButtonTapped(sender: UIButton) {
print("cancelButtonTapped")
}
func centerPictureFromPoint(point: CGPoint, ofSize size: CGSize, withCornerRadius radius: CGFloat) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.backgroundColor = UIColor(colorLiteralRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}) { (finished: Bool) -> Void in
}
}
I think the problem lies in my CathyTaskLogMessageViewController, when I change the code from
self.view.addSubview(imageViewerViewController.view) to self.presentViewController(imageViewerViewController, animated: true, completion: nil), my add target function gets called. Here's the code:
func defaultPictureButtonTapped(sender: UIButton) {
let imageViewerViewController = ImageViewerViewController()
imageViewerViewController.image = self.defaultPictureButton.imageView!.image
imageViewerViewController.cancelButtonImage = UIImage(named: "cancelButtonImage")
self.view.addSubview(imageViewerViewController.view)
imageViewerViewController.centerPictureFromPoint(self.defaultPictureButton.frame.origin, ofSize: self.defaultPictureButton.frame.size, withCornerRadius: self.defaultPictureButton.layer.cornerRadius)
// self.presentViewController(imageViewerViewController, animated: true, completion: nil)
}
However, I don't want to present a view controller. I want to add it as a subview. Anybody have any idea to fix this? And thank you so much for your help in advance.
The issue is in how you add child view controller.
You need to call addChildViewController(imageViewerViewController) before self.view.addSubview(imageViewerViewController.view)
Once what happened to me while using subviews was that the view was in front of the subview and hence the button on the subview was not getting tapped.
Try this:-
imageViewerViewController.view.layer.zPosition = 2
//You can set any value in place of 2 which is greater than zposition value of the view
self.view.addSubview(imageViewerViewController.view)
Hope this works.

Resources