change color of uiimageview in a empty array by pressing on it - swift

My swift code below has a button and when touch places a imageview on the viewcontroller. The only thing I want to do is when a individual imageview not all of the imageview just the one select is touch I would like to change the color from purple to blue only if touched and one at a time.
import UIKit
class ViewController: UIViewController {
var count: Int = 0
var ht = -90
var ww = 80
var moveCounter = 0
var counter = 0
var arrTextFields = [UIImageView]()
var b7 = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[b7].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}
b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)
}
//func that adds imageview.
#objc func addBOx() {
let subview = UIImageView()
subview.isUserInteractionEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)
subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)
subview.backgroundColor = .purple
subview.tag = count
count += 1
ht += 50
arrTextFields.append(subview)
}}

You already set the isUserInteractionEnabled property of the image view to true. To respond to touch events, create a UITapGestureRecognizer and add it to the image view like so:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
subview.addGestureRecognizer(gestureRecognizer)
Then inside of the imageViewTapped method you can extract the image view from the sender argument:
#objc func imageViewTapped(sender: UITapGestureRecognizer) {
if let imageView = sender.view as? UIImageView {
// Change the imageView's background here
}
}

Related

I want to make an if statement that each image would be full screen when the user is tap

here is the code that I check if they images are tapped but only the 3 image is apply full screen. As you can see I set the image is tapped to statusImageView to call the function of zoomImage So I want fixed for all images.
func imageTapped() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))
if detailsImage[0].tag == 0 {
detailsImage[0].isUserInteractionEnabled = true
detailsImage[0].addGestureRecognizer(tapGestureRecognizer)
self.statusImageView = detailsImage[0]
}
let tapGestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))
detailsImage[1].isUserInteractionEnabled = true
detailsImage[1].addGestureRecognizer(tapGestureRecognizer1)
self.statusImageView = detailsImage[1]
let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageZoom(tapGestureRecognizer:)))
detailsImage[2].isUserInteractionEnabled = true
detailsImage[2].addGestureRecognizer(tapGestureRecognizer2)
self.statusImageView = detailsImage[2]
}
let blackBackgroundColor = UIView()
let tappedImage = UIImageView()
var statusImageView: UIImageView?
let navigationBarView = UIView()
#objc func imageZoom(tapGestureRecognizer: UITapGestureRecognizer) {
annimationImage(detailsImage: statusImageView!)
}
And then I call the annihilationImage function which is takes the statusImageView as input
func annimationImage(detailsImage: UIImageView) {
if let startingFrame = statusImageView?.superview?.convert(statusImageView!.frame, to: nil) {
statusImageView!.alpha = 0
blackBackgroundColor.frame = self.view.frame
blackBackgroundColor.backgroundColor = UIColor.black
blackBackgroundColor.alpha = 0
view.addSubview(blackBackgroundColor)
navigationBarView.frame = CGRect(x: 0, y: 0, width: 1000, height: 100)
navigationBarView.backgroundColor = UIColor.black
navigationBarView.alpha = 0
if let keyWindow = UIApplication.shared.keyWindow {
keyWindow.addSubview(navigationBarView)
}
let tappedImage = UIImageView()
tappedImage.backgroundColor = .gray
tappedImage.frame = startingFrame
tappedImage.contentMode = .scaleToFill
tappedImage.isUserInteractionEnabled = true
tappedImage.image = statusImageView?.image
tappedImage.clipsToBounds = true
view.addSubview(tappedImage)
UIView.animate(withDuration: 0.75, animations: {
tappedImage.frame = CGRect(x: 0, y: y, width: self.view.frame.size.width, height: 300)
})
}
}
I want to make an if statement that while check which image is tapped
You can use tapGestureRecognizer.view for getting a view that is assigned a tap gesture. And by this, you can also get the view tag (your view is corresponding to the image view in your code)
#objc func imageZoom(tapGestureRecognizer: UITapGestureRecognizer) {
let senderView = tapGestureRecognizer.view // Here you get a view that is associated with the gesture
let tag = senderView?.tag // Here you get a tag that is assigned to all image
// Add your condition here by tag
annimationImage(detailsImage: statusImageView!)
}

Use Uitapgesture recognizer on multiple image views that are not declared

My swift code uses func addBox to add and append image views to the uiview controller. All I want to do is when one of the image views are tapped is for func viewClicked to be activated. Right now nothing is happening and nothing is being written into the debug area.
import UIKit
class ViewController: UIViewController {
var ht = -90
var ww = 80
var hw = 80
var arrTextFields = [UIImageView]()
var b7 = UIButton()
override func viewDidLoad() {
[b7].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}
b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}
//func that adds imageview.
#objc func addBOx() {
let subview = UIImageView()
subview.isUserInteractionEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)
subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)
subview.backgroundColor = .purple
ht += 50
arrTextFields.append(subview)
}
}
You need to enable user interation
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}

use tap gesture reconigzier on multiple image views

My swift code below places 2 different image views on a uiview controller. When the user hits a imageivew I want that specific imageview to change color. I dont know how to apply the method to multiple image views. I think you would use the sender method.
import UIKit
class ViewController: UIViewController {
var slider = UISlider()
var image1 = UIImageView()
var image2 = UIImageView()
var with = 80
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
[slider,image1,image2].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}
slider.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: CGFloat(with), height: 30)
image1.frame = CGRect(x: view.center.x-115, y: view.center.y, width: CGFloat(with), height: 30)
image2.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: CGFloat(with), height: 30)
slider.minimumValue = 10
slider.maximumValue = 150
image1.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
image1.addGestureRecognizer(gestureRecognizer)
image2.addGestureRecognizer(gestureRecognizer)
}
#objc func imageViewTapped(sender: UITapGestureRecognizer) {
if let imageView = sender.view as? UIImageView {
imageView.backgroundColor = .yellow
}
}
}
I tried your code:
add below two lines to enable the user interaction as mentioned by #matt:
image1.isUserInteractionEnabled = true
image2.isUserInteractionEnabled = true
and create two separate objects for gesture:
let gestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
image1.addGestureRecognizer(gestureRecognizer1)
let gestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
image2.addGestureRecognizer(gestureRecognizer2)
Output:
Happy coding...
A UIGestureRecognizer is to be used with a single view. So, you need to create two seperate UITapGestureRecognizer object for two different views.
For example:-
let image1GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
image1.addGestureRecognizer(image1GestureRecognizer)
let image2GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
image2.addGestureRecognizer(image2GestureRecognizer)

Swift - detect touched coordinate of UIView

I am trying to make a custom jump bar which can be attached to UITableView.
What I want to achieve now is if user touches A and slides through Z, I want print out A, B, C, D..., Z. Currently, it only prints A, A, A...A. Is there anyway I can achieve it?
Each letter is UIButton subview of UIView.
class TableViewJumpBar{
let tableView: UITableView
let view: UIView
let jumpBar: UIView!
private var jumpIndexes: [Character]
init(tableView: UITableView, view: UIView){
self.view = view
self.tableView = tableView
jumpBar = UIView(frame: .zero)
jumpBar.backgroundColor = UIColor.gray
let aScalars = "A".unicodeScalars
let aCode = aScalars[aScalars.startIndex].value
jumpIndexes = (0..<26).map {
i in Character(UnicodeScalar(aCode + i)!)
}
}
func setFrame(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat){
guard jumpIndexes.count > 0 else{
print("Jump indexes cannot be empty")
return
}
//Remove jumpbar and remove all subviews
jumpBar.removeFromSuperview()
for subView in jumpBar.subviews{
subView.removeFromSuperview()
}
jumpBar.frame = CGRect(x: x, y: y, width: width, height: height)
let height = height/CGFloat(jumpIndexes.count)
for i in 0..<jumpIndexes.count{
let indexButton = UIButton(frame: CGRect(x:CGFloat(0.0), y: CGFloat(i)*height, width: width, height: height))
indexButton.setTitle(String(jumpIndexes[i]), for: .normal)
indexButton.addTarget(self, action: #selector(jumpIndexButtonTouched(_:)), for: .allEvents)
jumpBar.addSubview(indexButton)
}
self.view.addSubview(jumpBar)
}
///Touch has been begun
#objc private func jumpIndexButtonTouched(_ sender: UIButton!){
print(sender.titleLabel?.text)
}
this code works and print start and finish characters.
class ViewController: UIViewController {
#IBOutlet weak var myTableView: UITableView!
#IBOutlet weak var myView: UIView!
var startChar = ""
var finishChar = ""
override func viewDidLoad() {
super.viewDidLoad()
let table = TableViewJumpBar(tableView: myTableView, view: myView)
table.setFrame(x: 0, y: 0, width: 100, height: self.view.frame.size.height)
print(myView.subviews[0].subviews)
setPanGesture()
}
func setPanGesture() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(panRecognized))
self.myView.addGestureRecognizer(pan)
}
#objc func panRecognized(sender: UIPanGestureRecognizer) {
let location = sender.location(in: myView)
if sender.state == .began {
for button in myView.subviews[0].subviews {
if let button = button as? UIButton, button.frame.contains(location), let startCharacter = button.titleLabel?.text {
self.startChar = startCharacter
}
}
} else if sender.state == .ended {
for button in myView.subviews[0].subviews {
if let button = button as? UIButton, button.frame.contains(location), let finishCharacter = button.titleLabel?.text {
self.finishChar = finishCharacter
}
}
print("start with \(startChar), finish with \(finishChar)")
}
}
}
In your code I delete Button action. you can use labels instead Buttons.
class TableViewJumpBar {
let tableView: UITableView
let view: UIView
let jumpBar: UIView!
private var jumpIndexes: [Character]
init(tableView: UITableView, view: UIView){
self.view = view
self.tableView = tableView
jumpBar = UIView(frame: .zero)
jumpBar.backgroundColor = UIColor.gray
let aScalars = "A".unicodeScalars
let aCode = aScalars[aScalars.startIndex].value
jumpIndexes = (0..<26).map {
i in Character(UnicodeScalar(aCode + i)!)
}
}
func setFrame(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat){
guard jumpIndexes.count > 0 else{
print("Jump indexes cannot be empty")
return
}
jumpBar.removeFromSuperview()
for subView in jumpBar.subviews{
subView.removeFromSuperview()
}
jumpBar.frame = CGRect(x: x, y: y, width: width, height: height)
let height = height/CGFloat(jumpIndexes.count)
for i in 0..<jumpIndexes.count{
let indexButton = UIButton(frame: CGRect(x:CGFloat(0.0), y: CGFloat(i)*height, width: width, height: height))
indexButton.setTitle(String(jumpIndexes[i]), for: .normal)
jumpBar.addSubview(indexButton)
}
self.view.addSubview(jumpBar)
}
}
Some output results:

UISwipeGestureRecognizer not recognized when added to UIView's subviews

I currently have a subclass of UIView which contains numerous subviews. I wish to add a UISwipeGesture to the subviews but unfortunately the swipe gesture is not recognized. I've set userInteractionEnabled = true and direction of the swipe gesture but nothing works.
public class CardStackView: UIView{
public var dataSource = [UIImage]()
private var swipeGuesture: UISwipeGestureRecognizer!
override public func layoutSubviews() {
for img in dataSource{
let view = AppView(image: img, frame: self.frame)
self.addSubview(view)
}
animateSubview()
self.userInteractionEnabled = true
}
func animateSubview(){
for (index, sView) in self.subviews.enumerate() {
swipeGuesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGuestureDidSwipeRight(_:)))
swipeGuesture.direction = .Right
sView.addGestureRecognizer(swipeGuesture)
sView.userInteractionEnabled = true
let move: CGFloat = CGFloat(-20 + index * 20)
let opacity = Float(1 - 0.2 * CGFloat(index))
sView.shadowOpacity(opacity).shadowOffset(CGSizeMake(20 - CGFloat(index) * 5, 20 - CGFloat(index) * 5)).shadowRadius(5).moveX(-move).moveY(-move).gravity().shadowColor(UIColor.grayColor()).duration(1)
.completion({
}).animate()
}
}
func swipeGuestureDidSwipeRight(gesture: UISwipeGestureRecognizer) {
print("Swiped right")
let subview = self.subviews[0]
subview.moveX(-60).duration(1).animate()
}
}
Example
class ExampleController: UIViewController {
var stackView: CardStackView!
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
self.view.addSubview(stackView)
}
}
self.view.bringSubviewToFront(yourSubview)
try this code for all your subviews and if it doesn't work try this in your controller class for your CardStackView.
Try to call setNeedsLayout for stackView:
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
stackView.setNeedsLayout()
self.view.addSubview(stackView)
}