Swift 3 game button pressed loop - ios

I have an array of images if I pressed the button the image will randomly appear. and there is an image down also called from the array but it appears randomly just once I opened the game. I want to do a conditions statement for button pressed. like I have 5 conditions once the button clicked: 1- if pressed and the image appeared is not same as the UIIMage view down score will be added
2- if button did not press for 2 seconds will appear down.
3- if button pressed and it is same as the UIimage so game over.
4- If he calculated 4 images down because he didn't hit the image in 2 seconds he will lose.
var array:[UIImage] = [UIImage(named: "1.png")!,
UIImage(named: "2.png")!,
UIImage(named: "3.png")!,
UIImage(named: "4.png")!,
UIImage(named: "5.png")!,
UIImage(named: "6.png")!,
UIImage(named: "7.png")!,
UIImage(named: "8.png")!,
UIImage(named: "9.png")!,
UIImage(named: "10.png")!]
var random = arc4random_uniform(10)
#IBAction func myButtonPressed(button: UIButton) {
var randomNum: UInt32 = 10
randomNum = arc4random_uniform(UInt32(array.count))
myButton.setImage(UIImage(named: "bird\(randomNum).png"), for: UIControlState.normal)
// myButton.setImage(UIImage(named: "\(randomNum).png"), for: UI)
self.myImage.animationImages = array
let buttonWidth = myButton.frame.width
let buttonHeight = myButton.frame.height
// Find the width and height of the enclosing view
let viewWidth = myButton.superview!.bounds.width
let viewHeight = myButton.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
myButton.center.x = xoffset + buttonWidth / 2
myButton.center.y = yoffset + buttonHeight / 2
/* for i in array{
if myButton != myImage{
randomNum = arc4random_uniform(UInt32(array.count))
}
if else
} */
}

Perhaps you could try something like this. As for your first condition, what is your UIImage View Variable. Is it another UIImage View that is being displayed on the storyboard?
import UIKit
class ViewController: UIViewController {
var array: [UIImage] = [UIImage(named: "1.png")!,
UIImage(named: "2.png")!,
UIImage(named: "3.png")!,
UIImage(named: "4.png")!,
UIImage(named: "5.png")!]
#IBOutlet weak var myButton: UIButton!
var pressed: Bool = false;
var score: Int = 0;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//2nd Condition: if button did not press for 2 seconds will appear down
if(pressed == false){
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(ViewController.doSomething), userInfo: nil, repeats: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func isPressed(_ sender: UIButton) {
pressed = true;
var randomNum: UInt32 = 10
randomNum = arc4random_uniform(UInt32(array.count));
myButton.setImage(UIImage(named: "\(randomNum).png"), for: .normal)
// 1st Condition: if pressed and the image appeared is not same as the UIIMage view down score will be added
if( UIImage(named: "\(randomNum).png") != myButton.currentImage){
//Add View Down Score
score += 1;
}
// 3rd Condition: if button pressed and it is same as the UIimage so game over
else{
// Game Over
}
}
func doSomething() {
// Not sure what you mean by will appear down
print("Action")
}
}
I am not quite sure what your 4th condition does. Please clarify

Related

How do I identify what UIImageView was tapped when using the "tap gesture recognition" method? [duplicate]

I want to realize a sort of matrix editable by touch.
A series of black or white cell that if tapped switch form black to withe or viceversa.
For doing this i will use UIImageView arranged in stack view a Tap Gesture Recognizer. But how do I know which UIImageView was tapped? And in which way I can change the UIImage in the UIImageView?
If they are just white and black, it would be much simpler to use a UIView and set its backgroundColor to .white or .black. You can use the tag property of the UIViews to identify them.
In your gestureRecognizer handler, the recognizer.view tells you the view that triggered the gesture.
You can assign the tags in Interface Builder. For example, if you have an 8x8 array of squares, you could use a 2-digit number where the first digit is the row and the second digit is the column. Thus, your tags would be 11, 12, ..., 87, 88.
func squareTapped(recognizer: UIGestureRecognizer) {
if let view = recognizer.view {
let tag = view.tag
let row = tag / 10
let col = tag % 10
print("The view at row \(row), column \(col) was tapped")
if view.backgroundColor == .black {
view.backgroundColor = .white
} else {
view.backgroundColor = .black
}
}
}
If you do want to use images, then load the images as properties of your viewController and assign them based upon the row and column of your image. Here I have used an Outlet Collection to hold all of the UIImageViews. In Interface Builder, you'd connect each of your cells to the squares property.
class BoardViewController: UIViewController {
let blackImage = UIImage(named: "blackImage")!
let whiteImage = UIImage(named: "whiteImage")!
#IBOutlet var squares: [UIImageView]!
var recognizersAdded = false
func setUpBoard() {
for imageview in squares {
if !recognizersAdded {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(squareTapped))
imageview.addGestureRecognizer(recognizer)
imageview.isUserInteractionEnabled = true
}
let tag = view.tag
let row = tag / 10
let col = tag % 10
// Just for demo purposes, set up a checkerboard pattern
if (row + col) % 2 == 0 {
imageview.image = blackImage
} else {
imageview.image = whiteImage
}
}
recognizersAdded = true
}
func squareTapped(recognizer: UIGestureRecognizer) {
if let view = recognizer.view as? UIImageView {
let tag = view.tag
let row = tag / 10
let col = tag % 10
print("The view at row \(row), column \(col) was tapped")
if view.image == blackImage {
view.image = whiteImage
} else {
view.image = blackImage
}
}
}
}
The code I'm using now is this, it works well.
But I want to use a pan gesture (UIPanGetureRecognizer) to change colors of the UIView. How can I do?
class ViewController: UIViewController {
#IBOutlet weak var PrincipalRowStack: UIStackView!
let rowsNumber=10
let colsNumber=10
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
var rowsStack = [UIStackView]()
var images = [[UIView]]()
var gestRec = [[UITapGestureRecognizer]]()
for r in 0...rowsNumber-1 {
rowsStack.append(UIStackView())
rowsStack[r].axis = .horizontal
rowsStack[r].distribution = .fillEqually
images.append([UIView]())
gestRec.append([UITapGestureRecognizer]())
for c in 0...colsNumber-1{
images[r].append(UIView())
gestRec[r].append(UITapGestureRecognizer())
gestRec[r][c].addTarget(self, action: #selector(ViewController.Tap(_:)))
images[r][c].contentMode = .scaleToFill
images[r][c].layer.borderWidth = 1
images[r][c].layer.borderColor = UIColor(red:0.5, green:0.5, blue:0.5, alpha: 1.0).cgColor
images[r][c].addGestureRecognizer(gestRec[r][c])
rowsStack[r].addArrangedSubview(images[r][c])
}
}
for s in rowsStack{
PrincipalRowStack.addArrangedSubview(s)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Tap(_ recognizer: UITapGestureRecognizer) {
if let view = recognizer.view {
//let tag = view.tag
//let row = tag / 10
//let col = tag % 10
print("Tapped!")
if view.backgroundColor == .black {
view.backgroundColor = .white
} else {
view.backgroundColor = .black
}
}
}
}
I'solved adding a PanGestureRecognizer to the principalStackView and than i use this function with a hitTest to know which view should change color.
func pan(_ recognizer: UIPanGestureRecognizer){
if (recognizer.state == .began ||
recognizer.state == .changed)
{
let loc = recognizer.location(in: principalRowStack)
let view = principalRowStack.hitTest(loc, with: UIEvent())
view?.backgroundColor = .black
}
}
Assign a tag to each UIImageView and Add Tap gestures on them.
Upon tap on any view , you can get the image view tapped by :
UIImageView *imageView = gestureRecogniser.view

How to change UIButton without reset position?

I have made a draggable button
let buttonGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedButton(_:)))
menuButton.isUserInteractionEnabled = true
menuButton.addGestureRecognizer(buttonGesture)
When the button drag to certain position, image will be changed.
#objc func draggedButton(_ sender:UIPanGestureRecognizer){
self.view.bringSubview(toFront: menuButton)
let translation = sender.translation(in: self.view)
menuButton.center = CGPoint(x: menuButton.center.x + translation.x, y: menuButton.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
if(menuButton.center.x < 100){
menuButton.setImage(UIImage(named: "newimage"), for: UIControlState.normal)
}
}
But after setImage, button will reset position, how to prevent this?
Try setting button background image instead of button image. Since setting image will rescale its position.
I had same problem and heres my solution:
unset the image, make button blank with no graphics in it
create new UIImageView including your UIImages, for initial and second state
in viewDidLoad() in UIViewController set UIImageView.bounds = UIButton.bounds set the initial image
call UIButton.addSubview(UIImageView)
in your method where you are using UIButton.setImage() call UIImageView.image = UIImage
Heres an example:
class VC : UIViewController{
let image_initial : UIImage = UIImage("img_1")
let image_second : UIImage = UIImage("img_2")
let imageview_menu : UIImageView = UIImageView()
#IBOutlet weak var button_menu: UIButton!
override func viewDidLoad(){
super.viewDidLoad()
//...
self.imageview_menu.bounds = button_menu.bounds
self.imageview_menu.image = image_initial
self.button_menu.addSubview(imageview_menu)
//...
}
#objc func draggedButton(_ sender:UIPanGestureRecognizer){
//...your code
if(menuButton.center.x < 100){
imageview_menu.image = image_second
}
}
}
Hope this helps if you haven't found solution. :)

UITapGestureRecognizer Add Coordinates to an Array

I have an ImageView inside of a ScrollView.
Each time the user clicks on a point on the image a pin is set and the coordinates are printed out.
However, I'm trying to store multiple coordinates inside of an array.
The first 3 times the user clicks on the image, I need the coordinates to store inside refs1. The next 14-20 times inside spots1.
// MARK: - Outlets
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var sharkImage: UIImageView!
// MARK: - Properties
var refs1 :[Double] = []
var spots1 :[Double] = []
// MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 6.0
scrollView.delegate = self
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
self.sharkImage.isUserInteractionEnabled = true
self.sharkImage.addGestureRecognizer(tapGestureRecognizer)
}
// MARK: - Scroll View
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return sharkImage
}
// MARK: - Functions
func tapAction(sender: UITapGestureRecognizer) {
// Get points for the UIImageView
let touchPoint = sender.location(in: self.sharkImage)
print(touchPoint)
// Add pin to tap
let pin = UIImageView(frame: CGRect(x: touchPoint.x - 5, y: touchPoint.y - 5, width:10, height:10))
pin.image = UIImage(named: "photo-pin-red")
sharkImage.addSubview(pin)
}
Well first of all you could store the coordinates in a 2D array if you want to:
var refs1 :[[Double]] = []
var spots1 :[[Double]] = []
Then store a global variable called counter to keep track of the click count:
var counter = 0
And then in your tapAction do the following (see comments for descriptions):
func tapAction(sender: UITapGestureRecognizer) {
// increase counter with +1 for each click
counter += 1
if counter <= 3 { // first 3
refs1.append([Double(touchPoint.x), Double(touchPoint.y)])
} else if counter <= 23 { // next 14 - 20 clicks
counter = 0 // reset counter to start over again
spots1.append([Double(touchPoint.x), Double(touchPoint.y)])
}
}
Use a counter variable:
var count = 0
func tapAction(sender: UITapGestureRecognizer) {
count = conut + 1
// Check for count
if (count >= 14) {
// Do stuff
}
// Get points for the UIImageView
let touchPoint = sender.location(in: self.sharkImage)
print(touchPoint)
// Add pin to tap
let pin = UIImageView(frame: CGRect(x: touchPoint.x - 5, y: touchPoint.y - 5, width:10, height:10))
pin.image = UIImage(named: "photo-pin-red")
sharkImage.addSubview(pin)
}

How recognize which UIImageview I've tapped?

I want to realize a sort of matrix editable by touch.
A series of black or white cell that if tapped switch form black to withe or viceversa.
For doing this i will use UIImageView arranged in stack view a Tap Gesture Recognizer. But how do I know which UIImageView was tapped? And in which way I can change the UIImage in the UIImageView?
If they are just white and black, it would be much simpler to use a UIView and set its backgroundColor to .white or .black. You can use the tag property of the UIViews to identify them.
In your gestureRecognizer handler, the recognizer.view tells you the view that triggered the gesture.
You can assign the tags in Interface Builder. For example, if you have an 8x8 array of squares, you could use a 2-digit number where the first digit is the row and the second digit is the column. Thus, your tags would be 11, 12, ..., 87, 88.
func squareTapped(recognizer: UIGestureRecognizer) {
if let view = recognizer.view {
let tag = view.tag
let row = tag / 10
let col = tag % 10
print("The view at row \(row), column \(col) was tapped")
if view.backgroundColor == .black {
view.backgroundColor = .white
} else {
view.backgroundColor = .black
}
}
}
If you do want to use images, then load the images as properties of your viewController and assign them based upon the row and column of your image. Here I have used an Outlet Collection to hold all of the UIImageViews. In Interface Builder, you'd connect each of your cells to the squares property.
class BoardViewController: UIViewController {
let blackImage = UIImage(named: "blackImage")!
let whiteImage = UIImage(named: "whiteImage")!
#IBOutlet var squares: [UIImageView]!
var recognizersAdded = false
func setUpBoard() {
for imageview in squares {
if !recognizersAdded {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(squareTapped))
imageview.addGestureRecognizer(recognizer)
imageview.isUserInteractionEnabled = true
}
let tag = view.tag
let row = tag / 10
let col = tag % 10
// Just for demo purposes, set up a checkerboard pattern
if (row + col) % 2 == 0 {
imageview.image = blackImage
} else {
imageview.image = whiteImage
}
}
recognizersAdded = true
}
func squareTapped(recognizer: UIGestureRecognizer) {
if let view = recognizer.view as? UIImageView {
let tag = view.tag
let row = tag / 10
let col = tag % 10
print("The view at row \(row), column \(col) was tapped")
if view.image == blackImage {
view.image = whiteImage
} else {
view.image = blackImage
}
}
}
}
The code I'm using now is this, it works well.
But I want to use a pan gesture (UIPanGetureRecognizer) to change colors of the UIView. How can I do?
class ViewController: UIViewController {
#IBOutlet weak var PrincipalRowStack: UIStackView!
let rowsNumber=10
let colsNumber=10
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
var rowsStack = [UIStackView]()
var images = [[UIView]]()
var gestRec = [[UITapGestureRecognizer]]()
for r in 0...rowsNumber-1 {
rowsStack.append(UIStackView())
rowsStack[r].axis = .horizontal
rowsStack[r].distribution = .fillEqually
images.append([UIView]())
gestRec.append([UITapGestureRecognizer]())
for c in 0...colsNumber-1{
images[r].append(UIView())
gestRec[r].append(UITapGestureRecognizer())
gestRec[r][c].addTarget(self, action: #selector(ViewController.Tap(_:)))
images[r][c].contentMode = .scaleToFill
images[r][c].layer.borderWidth = 1
images[r][c].layer.borderColor = UIColor(red:0.5, green:0.5, blue:0.5, alpha: 1.0).cgColor
images[r][c].addGestureRecognizer(gestRec[r][c])
rowsStack[r].addArrangedSubview(images[r][c])
}
}
for s in rowsStack{
PrincipalRowStack.addArrangedSubview(s)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Tap(_ recognizer: UITapGestureRecognizer) {
if let view = recognizer.view {
//let tag = view.tag
//let row = tag / 10
//let col = tag % 10
print("Tapped!")
if view.backgroundColor == .black {
view.backgroundColor = .white
} else {
view.backgroundColor = .black
}
}
}
}
I'solved adding a PanGestureRecognizer to the principalStackView and than i use this function with a hitTest to know which view should change color.
func pan(_ recognizer: UIPanGestureRecognizer){
if (recognizer.state == .began ||
recognizer.state == .changed)
{
let loc = recognizer.location(in: principalRowStack)
let view = principalRowStack.hitTest(loc, with: UIEvent())
view?.backgroundColor = .black
}
}
Assign a tag to each UIImageView and Add Tap gestures on them.
Upon tap on any view , you can get the image view tapped by :
UIImageView *imageView = gestureRecogniser.view

Swift : UIPageControl auto swipe in iOS 9

I've ImageView placed inside UICollectionViewCell and a PageControl below it. Both are connected via programmatically.
However, I want auto swipe (say every 5 seconds) the images should auto swipe. If user swipe manually then too it should happen. Also, when page control reaches to last it should begin with first.
Below is code that I've used :
var offersImages: [UIImage] = [ //Array of Banners
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
]
override func viewDidLoad() {
super.viewDidLoad()
self.objPageControl.currentPage = 0
self.objPageControl.numberOfPages = self.offersImages.count
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let pageWidth : CGFloat = self.objBannerCollectionView.frame.size.width
self.objPageControl.currentPage = Int(self.objBannerCollectionView.contentOffset.x/pageWidth)
}
How can this be done in Swift?
Refer following link , it will help to resolve your problem.
Horizontal Paging
Below code solved my problem :
//MARK:- viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
. . .
_ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(moveToNextPage), userInfo: nil, repeats: true)
}
func moveToNextPage (){
let pageWidth:CGFloat = self.objBannerCollectionView.frame.width
let maxWidth:CGFloat = pageWidth * 4
let contentOffset:CGFloat = self.objBannerCollectionView.contentOffset.x
var slideToX = contentOffset + pageWidth
if contentOffset + pageWidth == maxWidth {
slideToX = 0
}
self.objBannerCollectionView.scrollRectToVisible(CGRect(x:slideToX, y:0, width:pageWidth, height:self.objBannerCollectionView.frame.height), animated: true)
}

Resources