I want to swipe right to show another view and swipe left to get back to first view, Without using storyboard
like this example:
Could someone show me how to do that with swift 4
I would assume that if you were to use a swipe gesture, you would do something like:
let swipeGesture = UISwipeGestureRecognizer()
let scrollView = UIScrollView()
swipeGesture.direction = .right
swipeGesture.addTarget(self, action: #selector(scrollToBeginning))
#objc func scrollToBeginning() {
scrollView.setContentOffset(.zero, animated: true)
}
Or using scrollView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
Related
I am working with gestures first time here. Please let me know if my approach is wrong or any better solution.
I am trying to delete the collectionView Cell on swiping Left just like UITableview delete function. Deleting works fine. Now what I want is, Once I swipe the cell and tap anywhere on COllectionView it should swipe back to its original position(same like tableview delete row functionality)
I am using/trying this code
Updated viewDidLoad and tapped event
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
self.view.addGestureRecognizer(tap)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CustomCell
Cell.backgroundColor = UIColor.white
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(delete(sender:)))
leftSwipe.direction = UISwipeGestureRecognizerDirection.left
Cell.addGestureRecognizer(leftSwipe)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
Cell.addGestureRecognizer(tap)
Cell.deleteButton.addTarget(self, action: #selector(DeleteCell(sender:)), for: .touchUpInside)
}
func tapped(_ recognizer: UITapGestureRecognizer) {
// self.collectionView.performBatchUpdates({
//self.collectionView.reloadSections(NSIndexSet(index: 0) as IndexSet)
//}, completion: nil)
let point = recognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: point)
let cell = self.collectionView.cellForItem(at: indexPath!)
UIView.animate(withDuration: 0.4) {
cell?.contentView.frame = CGRect(x: 0, y: 0, width: (cell?.contentView.frame.width)!, height: (cell?.contentView.frame.height)!)
}
}
func delete(sender: UISwipeGestureRecognizer){
let cell = sender.view as! CustomCell
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: -90, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
}
func DeleteCell(sender : AnyObject){
let cell = sender.superview as! CustomCell
let i = self.collectionView.indexPath(for: cell)!.item
let indexpath = self.collectionView.indexPath(for: cell)
let array : NSMutableArray = []
self.collectionView.performBatchUpdates({
self.userArray.remove(at: i)
array.add(indexpath!)
self.collectionView.deleteItems(at:array as! [IndexPath])
}, completion: nil)
}
class CustomCell: UICollectionViewCell {
let deleteButton: UIButton = {
let deleteBtn = UIButton()
deleteBtn.setImage(UIImage(named: "red"), for: .normal)
deleteBtn.contentMode = .scaleAspectFit
return deleteBtn
}()
}
So here I am able to set the cell's position back to original by self.collectionView.performBatchUpdates but its not smooth animation. I tried using
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: 0, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
but it works only if swiped cell tapped, not any other cell or anywhere else. Any suggestions would be helpful!!
Right now you are accessing your cell from within itself. The reason it only works to tap on the cell you just swiped is because that is the only cell with that specific instance of UITapGestureRecognizer. To fix this, you should add that tap gesture recognizer to your whole view. Try adding this to your viewDidLoad() method:
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
self.view.addGestureRecognizer(tap)
Finally, got the solution.
Here is the demo project I found - CollectionViewSlideLeft
Hope it will help someone like me. :)
I have a subview from another view controller, whenever my scroll arrives on it, the subview change it's position to x = 0 and y = 0, below my navigation bar, but if I scroll fast and not stop on that view, everything is fine.
the code I use for addSubView is :
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "saleView") as! SaleViewController
self.addChildViewController(popOverVC)
popOverVC.view.frame = CGRect(x: 0 , y: 0 , width: saleTopView.frame.width, height: saleTopView.frame.size.height)
saleTopView.addSubview(popOverVC.view)
what I miss? thanks
add
popOverVC.didMove(toParentViewController : self)
at the end. Not a must do, but for simplicity, you could also rewrite
popOverVC.view.frame = self.saleTopView.frame
I have a simple test application and I want to pan an image inside its view. It will not pan or zoom and I can't see what's wrong with my code.
I have followed this tutorial but implemented it in code. I've made the image width the same as the height so I can pan without necessarily zooming.
Here is my code
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
return scrollView
}()
let zoomImageView: UIImageView = {
let imageView = UIImageView()
imageView.isUserInteractionEnabled = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.image = #imageLiteral(resourceName: "lighthouse")
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let screenSize = UIScreen.main.bounds
let screenHeight = screenSize.height
scrollView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 3.0
zoomImageView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)
scrollView.addSubview(self.zoomImageView)
view.addSubview(scrollView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomImageView
}
}
Search in your code for the term contentSize. You don't see it, do you? But the most fundamental fact about how a scroll view works is this: a scroll view without a contentSize cannot scroll (i.e. "pan" as you put it). In particular, it must have a content size larger than its own bounds size in order to be able to scroll along that axis (height or width, or both). Otherwise, there is nothing to scroll.
I want to create an alert with textfield and picker view.
I want that at top show picker view first and then textfield below picker view.
Here is my code
let alert = UIAlertController(title: "Create Meditation", message: "myMsg", preferredStyle: .alert)
alert.view.addSubview(pickerView)
alert.addTextField { (textField) in
textField.text = "Enter Message"
}
let action = UIAlertAction(title: "Send", style: .default) { (action) in
let textField = alert.textFields
print(textField)
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(action2)
let height:NSLayoutConstraint = NSLayoutConstraint(item: alert.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: self.view.frame.height * 0.50)
alert.view.addConstraint(height);
self.present(alert, animated: true, completion: nil)
You should create a uiviewcontroller and give it this effect.
For example: In the next image, i created a view as modal. it is a uiviewcontroller with a gray view (In your case, in the gray view you should put the uitextfield and uipickerview). Then, i configure storyboard segue as present modally and to give the effect of the modal in the uiviewcontroller put:
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8)
You can use the following code :
let alertView = UIAlertController(
title: "Select",
message: "\n\n\n\n\n\n\n\n\n",
preferredStyle: .alert)
let pickerView = UIPickerView(frame:
CGRect(x: 0, y: 50, width: 260, height: 162))
pickerView.dataSource = self
pickerView.delegate = self
pickerView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
alertView.view.addSubview(pickerView)
alertView.addTextField(configurationHandler: configurationTextField)
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
alertView.addAction(UIAlertAction(title: "Ok", style: .default, handler:{ (UIAlertAction) in
guard let text = self.textField?.text else {return}
print(text)
}))
present(alertView, animated: true, completion: {
pickerView.frame.size.width = alertView.view.frame.size.width
})
You can't use UIAlertController for that, as it doesn't have an option to add views other than textfields.
So, you have to write your own control, that will mimic UIAlertController.
You can write view controller and present it modally, or create a view and add it to the controller view.
Also, could be good idea to try to find ready component on github.com or cocoacontrols.com and modify it as you need it.
try these Pods hope it helps you
https://github.com/nealyoung/NYAlertViewController
First post and I'll be honest, I'm pretty bad at coding. I'm working with Swift 3 for a school project and I have a question.
I'm creating multiple subviews through a for in loop through an array...
...and each created subview contains one programmatically created label, each with a different word, and a programmatically created UI Tap Gesture attached to each view...
Import UIKit
class ViewController: UIViewController, UIGestureRecongizerDelegate
{
var array = ["Each","One","Has","Its","Own","Name"]
var label = UILabel()
var DynamicView = UIView()
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
createSubView()
//end SuperView
}
func createSubview()
{
for thing in array {
var string = array[count]
count = count + 1
DynamicView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 160))
DynamicView.center = CGPoint(x: xV,y: yV)
DynamicView.backgroundColor = UIColor.gray
self.view.addSubview(DynamicView)
label = UILabel(frame: CGRect(x: 25, y: 25, width: 100, height: 21))
label.center = CGPoint(x: 60, y: 13)
label.textAlignment = .center
label.font = UIFont(name: "Arial", size: 13)
label.text = "\(string)"
self.DynamicView.addSubview(label)
let tapGesture = UITapGestureRecognizer(target: self, action:
#selector(ViewController.tapped(recignizer:)))
DynamicView.isUserInteractionEnabled = true
DynamicView.addGestureRecognizer(tapGesture)
}
}
func tapped (recignizer:UITapGestureRecognizer){
print("\(label.text!)")
}
}
... (I'm excluding the code that separates all the views from being stacked on top of each other, so please assume that these views are spaced out, and this list of views is in a scroll view in my actual code, just not cramming that spaghetti code in here)...
...The result of the code is a layout of subViews, each with its own label that is a different word, and a tap gesture for each subView which triggers a function...
...What I want is a way to tap on each subview and find what the text in the label is. As of right now, when you tap on a view, you get what the label.text was in the last View made, so the result of print("label.text!") --> 'Name' , which makes some sense.
Is there any possible way to find the specific labels text even though they are all called "Label"?
I'm not looking to do a collection view or anything of the sort, I need something of this sort of coding to get what I need done.
Thank you to whoever helped this foolish swift student, sorry that my Swift lingo is hot garbage like my code.
Your problem is you are initializing the same DynamicView and label inside the for loop so it will overwrite and it will have last value from the array. To solved the problem you need to create separate UIView and separate UILabel in for loop. Also you need to set userInteraction of label to true because by default its false.
for thing in array {
let dynamicView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 160))
dynamicView.center = CGPoint(x: xV,y: yV)
dynamicView.backgroundColor = UIColor.gray
self.view.addSubview(dynamicView)
let label = UILabel(frame: CGRect(x: 25, y: 25, width: 100, height: 21))
label.center = CGPoint(x: 60, y: 13)
label.textAlignment = .center
label.font = UIFont(name: "Arial", size: 13)
label.text = thing
self.dynamicView.addSubview(label)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped(recignizer:)))
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tapGesture)
}
Now your all view’s origin is CGPoint.zero so only last view label will visible and when you tap on label to get text of its you can get this way.
func tapped(recignizer:UITapGestureRecognizer){
if let tappedLabel = recignizer.view as? UILabel {
print("\(tappedLabel.text)”)
}
}