can't set up UISwitch in Swift 4 - ios

Getting rustily back into iOS programming after some years away and am having trouble setting up a UISwitch. Here's my code:
#IBOutlet weak var firstConjugationVerbSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
firstConjugationVerbSwitch.addTarget(self, action: #selector(changeText), for: .valueChanged)
}
#objc func changeText() {
print("changeText function running.")
}
The error I get when I toggle the switch is
[Latin_Substitution_Drills.VerbOptionsViewController firstConjugationVerbSwitch:]: unrecognized selector sent to instance 0x7ffcea817600
Any thoughts about what I'm doing wrong?

let customSwitch = UISwitch(frame:CGRect(x: 20, y: 20, width: 0, height: 0))
customSwitch.isOn = false
customSwitch.onTintColor = UIColor(red: 10/255, green: 105/255, blue: 122/255, alpha: 1)
//customSwitch.setOn(true, animated: true)
customSwitch.transform = CGAffineTransform(scaleX: 0.60, y: 0.60)
customSwitch.addTarget(self, action: #selector(switchTarget(sender:)), for: .valueChanged)
let switchButton = UIBarButtonItem(customView: customSwitch)
#objc func switchTarget(sender: UISwitch!)
{
if sender.isOn {
// do something ..
} else{
// do something ..
}
}

Related

Why bottom line for text field does not follow the constraints rule in Swift?

This is my Utilities file in my project where I set the bottom line for the text field:
import Foundation
import UIKit
class Utilities {
static func styleTextField(_ textfield:UITextField) {
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0, y: textfield.frame.height - 2, width: textfield.frame.width, height: 2)
bottomLine.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1).cgColor
textfield.borderStyle = .none
textfield.layer.addSublayer(bottomLine)
}
static func styleFilledButton(_ button:UIButton) {
button.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
button.layer.cornerRadius = 25.0
button.tintColor = UIColor.white
}
static func styleFilledButtonweb(_ button:UIButton) {
button.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
button.layer.cornerRadius = 5.0
button.tintColor = UIColor.white
}
static func styleHollowButton(_ button:UIButton) {
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1).cgColor
button.layer.cornerRadius = 25.0
button.tintColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
}
}
And this is my View Controller file for using the styleTextField function:
import UIKit
import FirebaseAuth
import Firebase
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var firstNameTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Ad"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
firstNameTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var lastNameTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Soyad"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
lastNameTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var emailTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Email"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
emailTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var passwordTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Şifre"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
passwordTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var passworddogrulaTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Şifreyi Doğrula"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
passworddogrulaTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var signUpButton: UIButton!
#IBOutlet weak var errorLabel: UILabel!
let Button = UIButton(type: .custom)
let Button1 = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
setUpElements()
show_hide_password(textfield: passwordTextField)
show_hide_password1(textfield: passworddogrulaTextField)
self.passwordTextField.delegate = self
self.passworddogrulaTextField.delegate = self
self.emailTextField.delegate = self
self.lastNameTextField.delegate = self
self.firstNameTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
vself.view.endEditing(true)
return false
}
func show_hide_password(textfield: UITextField) {
textfield.rightViewMode = .unlessEditing
Button.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
Button.imageEdgeInsets = UIEdgeInsets(top: 5, left: -24, bottom: 5, right: 15)
Button.frame = CGRect(x: CGFloat(textfield.frame.size.width - 25), y: CGFloat(5), width: CGFloat(15), height: CGFloat(25))
Button.addTarget(self, action: #selector(self.btnVisibilityClicked), for: .touchUpInside)
textfield.rightView = Button
textfield.rightViewMode = .always
}
func show_hide_password1(textfield: UITextField) {
textfield.rightViewMode = .unlessEditing
Button1.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
Button1.imageEdgeInsets = UIEdgeInsets(top: 5, left: -24, bottom: 5, right: 15)
Button1.frame = CGRect(x: CGFloat(textfield.frame.size.width - 25), y: CGFloat(5), width: CGFloat(15), height: CGFloat(25))
Button1.addTarget(self, action: #selector(self.btnVisibilityClicked1), for: .touchUpInside)
textfield.rightView = Button1
textfield.rightViewMode = .always
}
#IBAction func btnVisibilityClicked(_ sender: Any) {
(sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
if (sender as! UIButton).isSelected{
self.passwordTextField.isSecureTextEntry = false
Button.setImage(UIImage(systemName: "eye.fill"), for: .normal)
} else {
self.passwordTextField.isSecureTextEntry = true
Button.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
}
}
#IBAction func btnVisibilityClicked1(_ sender: Any) {
(sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
if (sender as! UIButton).isSelected{
self.passworddogrulaTextField.isSecureTextEntry = false
Button1.setImage(UIImage(systemName: "eye.fill"), for: .normal)
} else {
self.passworddogrulaTextField.isSecureTextEntry = true
Button1.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
}
}
func setUpElements(){
errorLabel.alpha = 0
Utilities.styleTextField(firstNameTextField)
Utilities.styleTextField(lastNameTextField)
Utilities.styleTextField(emailTextField)
Utilities.styleTextField(passwordTextField)
Utilities.styleTextField(passworddogrulaTextField)
Utilities.styleFilledButton(signUpButton)
}
}
Here are the screenshots Connection for the text fields and the screenshot of sign up page storyboard for the storyboards and connections between storyboards and view controller:
Even though I declared the constraints, the bottom line does not appear right. What should I do for it to appear correct?
Here is the screenshot of the wrong appearance: The appearance of the text field in iPhone 12 Pro Max
And here is the screenshot of the correct appearance in the simulator of Xcode for iPhone 11: The simulator of iPhone 11 and the correct appearance
Thank you for your help! Here is the video link for the draft.
You are setting these before layouts set. If you had your view in a UIView class you could put these in layoutSubviews()
Since you are setting these in viewController, putting setUpElements() into viewDidAppear() will probably solve your problem.

Makpit Memory Leak

I tried a lot of solutions but even in actual device, memory consumption is very high. When secondview is dismissed first time, memory doesnot decrease like its increases. The memory usage after dismissing secondview depends on how much area user discovered in map.
Here is my code.
First view controller
import UIKit
import CoreLocation
class ViewController: UIViewController {
let manager = CLLocationManager()
private let currentColor = UIColor(red: 234/255.0, green: 128/255.0, blue: 16/255.0, alpha: 1.0)
override func viewDidLoad(){
super.viewDidLoad()
manager.requestWhenInUseAuthorization()
let button = buttonLoader(y: 7*self.view.frame.height/16, text: "trigger")
self.view.addSubview(button)
}
private func buttonLoader(y:CGFloat,text:String)->UIButton{
let Label = UIButton(frame: CGRect(x: 0, y: y , width: self.view.frame.width, height: self.view.frame.height/8))
Label.setTitle(text, for: .normal)
Label.addTarget(self, action: #selector(mapOpener), for: .touchUpInside)
Label.setTitleColor(currentColor, for: .normal)
self.view.addSubview(Label)
return Label
}
#objc func mapOpener(){
let newView = SecondViewController()
newView.view.backgroundColor = .white
self.present(newView, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
SecondViewController
import UIKit
import MapKit
class SecondViewController: UIViewController {
var map :MKMapView!
var saverButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
saveButtonLoader()
mapLoader()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapLoader(){
map = MKMapView(frame: CGRect(x: 0, y: 64, width: view.frame.size.width, height: self.view.frame.size.height-64))
map.mapType = MKMapType.standard
map.isZoomEnabled = true
map.isScrollEnabled = true
map.showsUserLocation = true
map.userTrackingMode = .follow
view.addSubview(map)
}
func saveButtonLoader() {
saverButton = UIButton(frame: CGRect(x: 4*view.frame.size.width/5, y: 20, width: view.frame.size.width/5, height: 44))
saverButton.setTitle("Finish", for: .normal)
saverButton.addTarget(self, action: #selector(finishButtonAction), for: UIControlEvents.touchUpInside)
saverButton.backgroundColor = UIColor.blue
saverButton.isEnabled = true
self.view.addSubview(saverButton)
}
override func viewWillDisappear(_ animated:Bool){
super.viewWillDisappear(animated)
self.applyMapViewMemoryFix()
}
func applyMapViewMemoryFix(){
map.delegate = nil
removeOldAnnotations()
map.removeFromSuperview()
map = nil
}
func removeOldAnnotations(){
for annotation in map.annotations{
map.removeAnnotation(annotation)
}
}
#objc func finishButtonAction(sender:UIButton!) {
self.dismiss(animated: true, completion: {
})
}
}

storyboard.instantiateViewController executes for about 3 seconds

I noticed that my app has a delay before presenting UIViewController, so I used print() to find out which line of code causing it and found up that let navigationVC = storyboard!.instantiateViewController(withIdentifier: "filterNavigationVC") as! UINavigationController executes for about 2 seconds. Why might it be like that? I've tried to remove everything except this one without even navigating and still it took that long.
#IBAction func filter(_ sender: AnyObject) {
let navigationVC = storyboard!.instantiateViewController(withIdentifier: "filterNavigationVC") as! UINavigationController
let destinationVC = navigationVC.topViewController as! FilterViewController
navigationVC.modalPresentationStyle = .overCurrentContext
destinationVC.backgroundColorValue = self.view.backgroundColor!
destinationVC.color = themeColor.light
destinationVC.delegate = self
destinationVC.billModel = self.price
destinationVC.applyedFilter = self.applyedFilter
self.present(navigationVC, animated: true, completion: nil)
}
Next UIViewController's viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
customization()
}
fileprivate func customization(){
setupBillButtons(billModel.range["low"]!, medium: self.billModel.range["medium"]!, high: self.billModel.range["high"]!)
tempConfigButtons([self.lowBillButton, self.mediumBillButton, self.highBillButton])
if color == themeColor.light {
customizeLightTheme()
} else if color == themeColor.dark {
customizeDarkTheme()
}
setCharacterSpacingForLabels([typeLabel, kitchenLabel, avarageBill, metroLabel, tagsLabel], spacing: 2.79)
setSeparatorInsets([kitchenTableView, metroTableView, typeTableView], edge: UIEdgeInsetsMake(0, 20, 0, 20))
backgroundVoew.backgroundColor = backgroundColorValue
backgroundVoew.addBackroundBlur()
self.navigationController?.navigationBar.isHidden = true
}
fileprivate func customizeDarkTheme() {
comfirmButton.setImage(UIImage(named: "comfirmLight"), for: UIControlState())
dismissButton.setImage(UIImage(named: "closeLight"), for: UIControlState())
setColorsForTableViews([kitchenTableView, metroTableView, typeTableView], separatorColor: colorWithAlpha(whiteColor, alpha: 0.05), tintColor: colorWithAlpha(whiteColor, alpha: 0.5))
setColorForLabels([kitchenLabel, avarageBill, metroLabel, typeLabel, tagsLabel], color: colorWithAlpha(whiteColor, alpha: 0.50))
topName.textColor = whiteColor
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
self.view.backgroundColor = backgroundColorValue
bottomComfitmButton.tintColor = whiteColor
bottomComfitmButton.backgroundColor = colorWithAlpha(whiteColor, alpha: 0.15)
showAllTags.titleLabel!.addCharactersSpacing(-0.39, text: (self.showAllTags.titleLabel?.text)!)
showAllTags.setTitleColor(colorWithAlpha(whiteColor, alpha: 0.5), for: UIControlState())
showAllFilterImage.image = UIImage(named: "filterShowAllDark")
}
fileprivate func customizeLightTheme() {
comfirmButton.setImage(UIImage(named: "comfirmDark"), for: UIControlState())
dismissButton.setImage(UIImage(named: "closeDark"), for: UIControlState())
setColorForLabels([kitchenLabel, avarageBill, metroLabel, typeLabel, tagsLabel], color: colorWithAlpha(grayColor, alpha: 0.50))
topName.textColor = grayColor
setColorsForTableViews([kitchenTableView, metroTableView, typeTableView], separatorColor: colorWithAlpha(grayColor, alpha: 0.1), tintColor: colorWithAlpha(grayColor, alpha: 0.59))
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
bottomComfitmButton.tintColor = grayColor
bottomComfitmButton.backgroundColor = colorWithAlpha(whiteColor, alpha: 0.25)
showAllTags.titleLabel!.addCharactersSpacing(-0.39, text: (self.showAllTags.titleLabel?.text)!)
showAllTags.setTitleColor(colorWithAlpha(grayColor, alpha: 0.5), for: UIControlState())
showAllFilterImage.image = UIImage(named: "filterShowAllLight")
}
fileprivate func setupBillButtons(_ low: Bool, medium: Bool, high: Bool) {
lowBillButton.isSelected = low
mediumBillButton.isSelected = medium
highBillButton.isSelected = high
}
fileprivate func setSeparatorInsets(_ tableViews: [UITableView], edge: UIEdgeInsets) {
for tableView in tableViews {
tableView.separatorInset = edge
}
}
fileprivate func tempConfigButtons(_ buttons: [UIButton]) {
for button in buttons {
button.setTitleColor(whiteColor, for: .selected)
if self.color == themeColor.dark {
button.setBackgroundColor(colorWithAlpha(whiteColor, alpha: 0.50), forState: .selected)
button.setTitleColor(whiteColor, for: UIControlState())
DispatchQueue.main.async(execute: {
button.roundCorners([.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 15, borderColor: self.colorWithAlpha(self.whiteColor, alpha: 0.50), borderWidth: 1)
})
} else {
button.setTitleColor(grayColor, for: UIControlState())
button.setBackgroundColor(colorWithAlpha(grayColor, alpha: 0.50), forState: .selected)
DispatchQueue.main.async(execute: {
button.roundCorners([.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 15, borderColor: self.grayColor, borderWidth: 1)
})
}
}
}

UISearchController with Google Maps using Swift

I'm trying to create a screen where there is going to be a Google map covering the whole screen and a button on the top showing the selected address (where the marker is pointing).
And I want when the user clicks on that button to be presented with a UISearchBar where he can search for locations using the Google Places API.
I have been following the following tutorial:
https://www.youtube.com/watch?v=gRQUoHleCGM
Unfortunately, in my case the search bar is not appearing (although the background is dimmed when I press the button).
Here are some screenshots from before I press the button and after.
And this is the code of my view controller.
class ChooseLocationViewController: UIViewController, GMSMapViewDelegate, UISearchBarDelegate, UISearchControllerDelegate {
let geocoder = GMSGeocoder()
var mapView: GMSMapView = GMSMapView.mapWithFrame(CGRectZero, camera:GMSCameraPosition.cameraWithLatitude(51.515339, longitude: -0.141838, zoom: 16))
var addressButton: UIButton = UIButton()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let marker = UIImageView(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
marker.image = UIImage(named: "default-marker")
marker.center.x = self.view.center.x
marker.center.y = self.view.center.y - (self.navigationController?.navigationBar.frame.size.height)!
addressButton = UIButton(frame: CGRect(x: 20, y: 20, width: self.view.frame.size.width - 25, height: 47))
addressButton.center.x = self.view.center.x
addressButton.backgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1.0)
addressButton.layer.borderColor = UIColor(red: 178/255, green: 178/255, blue: 178/255, alpha: 1.0).CGColor
addressButton.layer.borderWidth = 1.0
addressButton.layer.cornerRadius = 5
addressButton.setTitleColor(UIColor(red: 68/255, green: 68/255, blue: 68/255, alpha: 1.0), forState: .Normal)
addressButton.titleLabel?.font = UIFont.systemFontOfSize(13)
addressButton.addTarget(self, action: "showLocationSearch", forControlEvents: .TouchDown)
self.view = mapView
self.view.addSubview(marker)
self.view.addSubview(addressButton)
}
func showLocationSearch() {
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
searchController.searchBar.delegate = self
self.presentViewController(searchController, animated: true, completion: nil)
}
func willPresentSearchController(searchController: UISearchController) {
self.navigationController?.extendedLayoutIncludesOpaqueBars = true
}
func willDismissSearchController(searchController: UISearchController) {
self.navigationController?.extendedLayoutIncludesOpaqueBars = false
}
func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) {
let coordinate = position.target
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
if let address = response?.firstResult() {
if let lines = address.lines {
if (lines.count > 0) {
self.addressButton.setTitle(lines[0], forState: .Normal)
}
}
}
}
}
}
Also, the reason I'm changing the extendedLayoutIncludesOpaqueBars is because I noticed that in other views where I have a search bar, this is necessary for it to be presented properly. In this case, I get exactly the same behavior (search bar is not showing) whether I do that or not.
What am I doing wrong? Did anyone have a similar issue?

How to change size of UIButton if it is a certain size

I have looked at and tried many things but cannot find a way that will. What I am trying to do is create an if statement in my code that states that if one of the sender(a UIButton)'s dimensions, either height or width, are below 50, they would become a 50 x 50 UIButton equal to a randomColor() and randomPoint(). Thank you. Below is my code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(arc4random()%568))
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: 150, height: 150))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
sender.backgroundColor = UIColor.blackColor()
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
}
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(0.75, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I have updated my code but I still do not think it is working. I think it is because a lot of the time the squares are left as "L"s after a full overlapping square is clicked and you are left with an "L". Any way to fix this and make it so if will always work. My code is below in case it is actually or also something else?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(arc4random()%568))
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: 150, height: 150))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
sender.backgroundColor = UIColor.blackColor()
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
if sender.frame.height < 50 || sender.frame.width < 50 {
sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
sender.backgroundColor = self.randomColor()
sender.center = self.randomPoint()
return
}
}
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(0.75, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
If you're looking to make this check after the user pushes the button, you can add a check inside your buttonPressed: function like this:
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 = self.randomColor()
sender.center = self.randomPoint()
return
}
sender.backgroundColor = UIColor.blackColor()
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
}
This will see if the height or width is less than 50 points, and if it is it'll set the size to 50x50, set it to a random color, and set the center to the random point. It'll be an instant jump, though, so if you want to animate that you can do that instead. The return part will just ensure the rest of the code below doesn't get executed.

Resources