I have been trying to piece together a project that contains a collection view that scrolls on the side, and when a cell is tapped it will add a new image view to the scene. I would like this new image to be draggable.
My code currently shows the collection view and when tapped adds a new image (which I call stickers).
I haven't quite figured out how to make it place the correct sticker yet, but my first goal is to make sure what appears can be moved.
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var collectionView: UICollectionView!
let stickers: [UIImage] = [
UIImage(named: "cow")!,
UIImage(named: "chicken")!,
UIImage(named: "pig")!,
UIImage(named: "cow")!,
UIImage(named: "chicken")!,
UIImage(named: "pig")!,
UIImage(named: "cow")!,
UIImage(named: "chicken")!,
UIImage(named: "pig")!,
]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stickers.count
}
var activeSticker = UIImage(named: "cow")
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.stickerImage.image = stickers[indexPath.item]
cell.backgroundColor = UIColor(white: 1, alpha: 0.9)
cell.translatesAutoresizingMaskIntoConstraints = false
cell.contentMode = .scaleAspectFill
cell.clipsToBounds = true
cell.layer.cornerRadius = 7
let addSticker = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
addSticker.addTarget(self, action: #selector(addStickerTapped), for: UIControl.Event.touchUpInside)
activeSticker = cell.stickerImage.image
cell.addSubview(addSticker)
return cell
}
#IBAction func addStickerTapped() -> Void {
print("Hello Sticker Button")
let image = activeSticker //UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 200)
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
self.view.addSubview(imageView)
//Imageview on Top of View
self.view.bringSubviewToFront(imageView)
}
}
To move the imageView around inside self.view you can use UIPanGestureRecognizer. Add the gesture recognizer, for example, in viewDidLoad:
class ViewController: UIViewController {
var selectedImageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
addPanGestureRecognizer()
}
func addPanGestureRecognizer() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(moveImageView(_:)))
// set up and optimize pan gesture options here if you need to
self.view.addGestureRecognizer(pan)
}
#objc func moveImageView(_ sender: UIPanGestureRecognizer) {
// assign one of your image views to selectedImageView to ensure you only move one image view at a time
// for example in func addStickerTapped() you could assign selectedImageView = imageView
guard let selectedImageView = selectedImageView else {
return
}
switch sender.state {
case .changed, .ended:
selectedImageView.center = selectedImageView.center.offset(by: sender.translation(in: self.view))
sender.setTranslation(.zero, in: self.view)
default:
break
}
}
}
extension CGPoint {
func offset(by point: CGPoint) -> CGPoint {
return CGPoint(x: self.x + point.x, y: self.y + point.y)
}
}
Related
I have a view controller that contains a uicollectionview. Each collectionview cell contains a button that, when clicked, adds a new label within the cell. To expand the height of each cell I call reloadItems(at: [indexPath]).
Unfortunately calling reloadItems(at: [indexPath]) fades out the old label and fades in the new label, how do I prevent any labels from fading out?
The bug becomes even more apparent every time I click the addLabel button: a new label fades in but whatever previous labels had not been visible suddenly appear again and whatever labels used to be visible, magically turn invisible again.
reloadItems(at: [indexPath]) seems to toggle the alpha of each new label differently. I would like to resize and add new labels to the cell without having any labels disappear.
Here is my code:
ViewController
class ViewController: UIViewController {
weak var collectionView: UICollectionView!
var expandedCellIdentifier = "ExpandableCell"
var cellWidth:CGFloat{
return collectionView.frame.size.width
}
var expandedHeight : CGFloat = 200
var notExpandedHeight : CGFloat = 50
//the first Int gives the row, the second Int gives the amount of labels in the row
var isExpanded = [Int:Int]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<4 {
isExpanded[i] = 1
}
}
}
extension ViewController:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return isExpanded.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: expandedCellIdentifier, for: indexPath) as! ExpandableCell
cell.indexPath = indexPath
cell.delegate = self
cell.setupCell = "true"
return cell
}
}
extension ViewController:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if isExpanded[indexPath.row]! > 1{
let height = (collectionView.frame.width/10)
let newHeight = height * CGFloat(isExpanded[indexPath.row]!)
return CGSize(width: cellWidth, height: newHeight)
}else{
return CGSize(width: cellWidth, height: collectionView.frame.width/6 )
}
}
}
extension ViewController:ExpandedCellDeleg{
func topButtonTouched(indexPath: IndexPath) {
isExpanded[indexPath.row] = isExpanded[indexPath.row]! + 1
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.collectionView.reloadItems(at: [indexPath])
}, completion: { success in
print("success")
})
}
}
Protocol
protocol ExpandedCellDeleg:NSObjectProtocol{
func topButtonTouched(indexPath:IndexPath)
}
ExpandableCell
class ExpandableCell: UICollectionViewCell {
weak var delegate:ExpandedCellDeleg?
public var amountOfIntervals:Int = 1
public var indexPath:IndexPath!
var setupCell: String? {
didSet {
print("cell should be setup!!")
}
}
let ivAddLabel: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = #imageLiteral(resourceName: "plus")
imageView.tintColor = .black
imageView.contentMode = .scaleToFill
imageView.backgroundColor = UIColor.clear
return imageView
}()
override init(frame: CGRect) {
super.init(frame: .zero)
contentView.addSubview(ivAddLabel)
let name = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 18))
name.center = CGPoint(x: Int(frame.width)/2 , y: 20)
name.textAlignment = .center
name.font = UIFont.systemFont(ofSize: 16)
name.textColor = UIColor.black
name.text = "Fred"
contentView.addSubview(name)
ivAddLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -14).isActive = true
ivAddLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
ivAddLabel.widthAnchor.constraint(equalToConstant: 20).isActive = true
ivAddLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
ivAddLabel.layer.masksToBounds = true
ivAddLabel.isUserInteractionEnabled = true
let addGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ivAddLabelSelected))
ivAddLabel.addGestureRecognizer(addGestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func ivAddLabelSelected(){
print("add button was tapped!")
if let delegate = self.delegate{
amountOfIntervals = amountOfIntervals + 1
let height = (20*amountOfIntervals)
let name = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 18))
name.center = CGPoint(x: Int(frame.width)/2, y: height)
name.textAlignment = .center
name.font = UIFont.systemFont(ofSize: 16)
name.textColor = UIColor.black
name.text = "newFred"
name.alpha = 0.0
contentView.addSubview(name)
UIView.animate(withDuration: 0.2, animations: { name.alpha = 1.0 })
delegate.topButtonTouched(indexPath: indexPath)
}
}
}
It's because you animate the new label
UIView.animate(withDuration: 0.2, animations: { name.alpha = 1.0 })
and in parallel reload the cell which creates a new cell/reuses existing and shows it, but also you wrap the reload into animation block which seems strange and useless:
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.collectionView.reloadItems(at: [indexPath])
}, completion: { success in
print("success")
})
You need to remove both animations and just reload the cell. If you need a nice animation of cell expansion you need to implement collection layout which will handle all states - start, intermediate, end of the animation. It's hard.
Try to use suggested in other answer "UICollectionView Self Sizing Cells with Auto Layout" if it will not help, then either forgot the idea of animation or implement custom layout.
I'd suggest you read into self-sizing UICollectionViewCells (e.g. UICollectionView Self Sizing Cells with Auto Layout) and UIStackView (e.g. https://janthielemann.de/ios-development/self-sizing-uicollectionviewcells-ios-10-swift-3/).
You should use a UIStackView, with constraints to top and bottom edge of your cells contentView.
Then you can add your Labels as managedSubviews to your stackView. This will add the labels with animation.
With self-sizing cell you do not need to reloadItems and it should work as you expect.
I have a UIScrollView that I am trying to use as an Image Viewer. For this I have paging enabled and I add "Slides" to the view for each Image, including a UIImageView and multiple labels and buttons. This works perfectly while I only have a few Slides to show, but I will need to have more than 100 of them, and I am running into really bad performance issues.
When I present the ViewController, and therefore set up the ScrollView, I get a good 10-15s of delay. Apparently loading this many views is a little much.
So I was wondering if any of you had an idea how I could make this more efficient.
I have tried making the array of Slides in the previous VC, and passing it, instead of creating it on the spot, that helped a bit, but not enough to make it feel acceptable, especially since changing device orientation will require me to set the ScrollView up again (because the Slides height/width will be off).
Here are the functions to set up the Slides, and to present them on the ScrollView:
func createSlides() -> [Slide] {
print("creating Slides")
let Essence = EssenceModel.Essence
var ImageArray = [Slide]()
var slide: Slide
var count = 0
for img in Essence{
count += 1
slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
slide.imageView.image = UIImage(named: img.imageUrl)
slide.isUserInteractionEnabled = true
slide.textLabel.text = img.description
slide.likeButton.imageView?.contentMode = .scaleAspectFit
slide.hero.id = img.heroID
slide.tag = count
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
slide.imageView.addGestureRecognizer(tapGesture)
let dismissGesture = UITapGestureRecognizer(target: self, action: #selector(dismissVC))
slide.backButton.addGestureRecognizer(dismissGesture)
slide.backButton.isUserInteractionEnabled = true
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipedUp))
swipeUp.direction = .up
slide.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(swipedDown))
swipeDown.direction = .down
slide.addGestureRecognizer(swipeDown)
let slideRecognizer = UITapGestureRecognizer(target: self, action: #selector(startSlideshow))
slide.slideButton.addGestureRecognizer(slideRecognizer)
slide.likeButton.imageView?.contentMode = .scaleAspectFit
slide.setupZoom()
ImageArray.append(slide)
}
count = 0
print(ImageArray.count)
return ImageArray
}
func setupSlideScrollView(slides : [Slide]) {
scrollView.subviews.forEach { $0.removeFromSuperview() }
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height)
scrollView.isPagingEnabled = true
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
scrollView.addSubview(slides[i])
}
}
As I said, I am looking for ways of making this more efficient in any way so I can actually use it. Preferebly I would probably just load the Slide that I am on, the next and previous one, but I have no clue how I would go about doing that.
Here is also a Screenshot, so you can see what it looks like.
Would be better to do something like that:
1) Add UICollectionView
2) Add UITableViewCell with restorationID
3) Add relations to your controller/view
4) Set horizontal scroll direction: https://www.screencast.com/t/wmPiwVdY
5) And after that create logic something like that:
class ImageCollectionViewVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
private var images = [Slide]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let imageCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageSlideCellRestorationID", for: indexPath) as? ImageSlideCell else {
return ImageSlideCell()
}
imageCell.image.image = UIImage(named: images[indexPath.row].imageUrl)
return imageCell
}
}
class ImageSlideCell: UICollectionViewCell {
#IBOutlet weak var image: UIImageView!
}
Instead using uiscroll and got a performance problems. You should using uicollectionview, scroll horizontal, custom cell with one image and buttons.
I'm trying to replicate the swipe to delete functionality of iOS. I know it's instantly available on a tableview, but the UI that I need to build benefits from a Collection View. Therefor I need a custom implementation where I would be using a swipe up gesture. Luckily, that's something that I managed to implement myself, however I'm having a hard time figuring out how I need to setup the swipe to delete / tap to delete / ignore functionality.
The UI currently looks like this:
So I'm using the following collectionview:
func buildCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 4;
collectionView = UICollectionView(frame: CGRect(x: 0, y: screenSize.midY - 120, width: screenSize.width, height: 180), collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(VideoCell.self, forCellWithReuseIdentifier: "videoCell")
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.contentInset = UIEdgeInsetsMake(0, 20, 0, 30)
collectionView.backgroundColor = UIColor.white()
collectionView.alpha = 0.0
//can swipe cells outside collectionview region
collectionView.layer.masksToBounds = false
swipeUpRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.deleteCell))
swipeUpRecognizer.delegate = self
collectionView.addGestureRecognizer(swipeUpRecognizer)
collectionView.isUserInteractionEnabled = true
}
My custom videocell contains one image and below that there is the delete button. So if you swipe the image up the delete button pops up. Not sure if this is the right way on how to do it:
class VideoCell : UICollectionViewCell {
var deleteView: UIButton!
var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
deleteView = UIButton(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
deleteView.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(deleteView)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
imageView.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And I'm using the following logic:
func deleteCell(sender: UIPanGestureRecognizer) {
let tapLocation = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: tapLocation)
if velocity.y < 0 {
//detect if there is a swipe up and detect it's distance. If the distance is far enough we snap the cells Imageview to the top otherwise we drop it back down. This works fine already.
}
}
But the problem starts there. As soon as my cell is outside the collectionview bounds I can't access it anymore. I still want to swipe it further to remove it. I can only do this by swiping on the delete button, but I want the Imageview above it to be swipeable as well. Or if I tap the image outside the collectionview it should slide back into the line and not delete it.
If I increase the collectionview bounds I can prevent this problem but than I can also swipe to remove outside the cell's visible height. This is caused by the tapLocation that is inside the collectionview and detects an indexPath. Something that I don't want. I want the swipe up only to work on a collectionview's cell.
Also the button and the image interfere with each other because I cannot distinguish them. They are both in the same cell so that's why I'm wondering if I should have the delete button in the cell at all. Or where should I place it otherwise? I could also make two buttons out of it and disable user interaction depending on state, but not sure how that would end up.
So, if you want the swipes gesture recogniser to continue recording movement when they are outside of their collection view, you need to attach it to the parent of the collection view, so it's bounded to the full area where the user can swipe.
That does mean that you will get swipes for things outside the collection view, but you can quite easily ignore those using any number of techniques.
To register delete button taps, you'll need to call addTarget:action:forControlEvents: on the button
I would keep the cell as you have it, with the image and the button together. It will be much easier to manage, and they belong together.
To manage moving the image up and down, I would look at using a transform, or an NSLayoutConstraint. Then you just have to adjust one value to make it move up and down in sync with the user swipes. No messing with frames.
For my own curiosity's sake I tried to make a replicate of what you're trying to do, and got it to work somehow good. It differs from yours in the way I setup the swipe gestures as I didn't use pan, but you said you already had that part, and haven't spend too much time on it. Pan is obviously the more solid solution to make it interactive, but takes a little longer to calculate, but the effect and handling of it, shouldn't differ much from my example.
To resolve the issue not being able to swipe outside the cell I decided to check if the point was in the swiped rect, which is twice the height of the non-swiped rect like this:
let cellFrame = activeCell.frame
let rect = CGRectMake(cellFrame.origin.x, cellFrame.origin.y - cellFrame.height, cellFrame.width, cellFrame.height*2)
if CGRectContainsPoint(rect, point) {
// If swipe point is in the cell delete it
let indexPath = myView.indexPathForCell(activeCell)
cats.removeAtIndex(indexPath!.row)
myView.deleteItemsAtIndexPaths([indexPath!])
}
I created a demonstration with comments: https://github.com/imbue11235/swipeToDeleteCell
I hope it helps you in anyway!
If you want to make it mare generic:
Make a costume Swipeable View:
import UIKit
class SwipeView: UIView {
lazy var label: UILabel = {
let label = UILabel()
label.textColor = .black
label.backgroundColor = .green
return label
}()
let visableView = UIView()
var originalPoint: CGPoint!
var maxSwipe: CGFloat! = 50 {
didSet(newValue) {
maxSwipe = newValue
}
}
#IBInspectable var swipeBufffer: CGFloat = 2.0
#IBInspectable var highVelocity: CGFloat = 300.0
private let originalXCenter: CGFloat = UIScreen.main.bounds.width / 2
private var panGesture: UIPanGestureRecognizer!
public var isPanGestureEnabled: Bool {
get { return panGesture.isEnabled }
set(newValue) {
panGesture.isEnabled = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupGesture()
}
private func setupViews() {
addSubview(visableView)
visableView.addSubview(label)
visableView.edgesToSuperview()
label.edgesToSuperview()
}
private func setupGesture() {
panGesture = UIPanGestureRecognizer(target: self, action: #selector(swipe(_:)))
panGesture.delegate = self
addGestureRecognizer(panGesture)
}
#objc func swipe(_ sender:UIPanGestureRecognizer) {
let translation = sender.translation(in: self)
let newXPosition = center.x + translation.x
let velocity = sender.velocity(in: self)
switch(sender.state) {
case .changed:
let shouldSwipeRight = translation.x > 0 && newXPosition < originalXCenter
let shouldSwipeLeft = translation.x < 0 && newXPosition > originalXCenter - maxSwipe
guard shouldSwipeRight || shouldSwipeLeft else { break }
center.x = newXPosition
case .ended:
if -velocity.x > highVelocity {
center.x = originalXCenter - maxSwipe
break
}
guard center.x > originalXCenter - maxSwipe - swipeBufffer, center.x < originalXCenter - maxSwipe + swipeBufffer, velocity.x < highVelocity else {
center.x = originalXCenter
break
}
default:
break
}
panGesture.setTranslation(.zero, in: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SwipeView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
The embed swappable view in UICollectionViewCell:
import UIKit
import TinyConstraints
protocol DeleteCellDelegate {
func deleteCell(_ sender : UIButton)
}
class SwipeableCell: UICollectionViewCell {
lazy var deleteButton: UIButton = {
let button = UIButton()
button.backgroundColor = .red
button.addTarget(self, action: #selector(didPressedButton(_:)), for: .touchUpInside)
button.titleLabel?.text = "Delete"
return button
}()
var deleteCellDelegate: DeleteCellDelegate?
#objc private func didPressedButton(_ sender: UIButton) {
deleteCellDelegate?.deleteCell(sender)
print("delete")
}
let swipeableview: SwipeView = {
return SwipeView()
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(deleteButton)
addSubview(swipeableview)
swipeableview.edgesToSuperview()
deleteButton.edgesToSuperview(excluding: .left, usingSafeArea: true)
deleteButton.width(bounds.width * 0.3)
swipeableview.maxSwipe = deleteButton.bounds.width
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
A sample ViewController:
import UIKit
import TinyConstraints
class ViewController: UIViewController, DeleteCellDelegate {
func deleteCell(_ sender: UIButton) {
let indexPath = IndexPath(item: sender.tag, section: 0)
items.remove(at: sender.tag)
collectionView.deleteItems(at: [indexPath])
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: view.bounds.width, height: 40)
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .yellow
cv.isPagingEnabled = true
cv.isUserInteractionEnabled = true
return cv
}()
var items = ["1", "2", "3"]
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.edgesToSuperview(usingSafeArea: true)
collectionView.register(SwipeableCell.self, forCellWithReuseIdentifier: "cell")
let panGesture = UIPanGestureRecognizer()
view.addGestureRecognizer(panGesture)
panGesture.delegate = self
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SwipeableCell
cell.backgroundColor = .blue
cell.swipeableview.label.text = items[indexPath.item]
cell.deleteButton.tag = indexPath.item
cell.deleteCellDelegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
I have to implement a menu just like the "example.gif" in the following library link
i'm using this same library to blur the background.
i've used contentInset so that the first three rows show up from the bottom.
Now, my problem is when i start scrolling the entire screen is blurred, whereas i want to blur the part of screen where uitableviewcells are getting scrolled. (Ultimately, the entire screen will be blurred as soon as the first cell reaches the top).
how can i achieve this. If there is any workaround without using the library, it is also welcome. Here is the code--
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate{
#IBOutlet weak var table: UITableView!
var blurView: DKLiveBlurView!
var unsortedCountryArray:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let topInset = self.view.frame.height - 120
// Array to display.
let countryArray = NSLocale.ISOCountryCodes()
for countryCode in countryArray {
let displayNameString = NSLocale.currentLocale().displayNameForKey(NSLocaleCountryCode, value: countryCode)
if displayNameString != nil {
unsortedCountryArray.append(displayNameString!)
}
}
// =============setting background==============
// self.bkgView = UIImageView(frame: self.view.bounds)
// self.bkgView.image = UIImage(named: "bg1")
// self.bkgView.contentMode = .ScaleAspectFill
// self.view.addSubview(self.bkgView)
// self.blurredBkgView = UIImageView(frame: self.view.bounds)
// self.blurredBkgView.image = UIImage(named: "bg1")
// self.blurredBkgView.contentMode = .ScaleAspectFill
// self.view.addSubview(blurredBkgView)
// self.blurredBkgView.alpha = 0.0
//
// blurEffect = UIBlurEffect(style: .Light)
// visualEffectView = UIVisualEffectView(effect: blurEffect)
// visualEffectView.frame = self.blurredBkgView.bounds
// self.visualEffectView.alpha = 0.0
// self.view.addSubview(self.visualEffectView)
self.table.backgroundColor = UIColor.clearColor()
self.table.separatorColor = UIColor.clearColor()
self.table.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0)
self.table.rowHeight = 40
print("view bounds: \(self.view.bounds)\n and table bounds: \(self.table.bounds)")
self.blurView = DKLiveBlurView(frame: self.table.bounds)
self.blurView.originalImage = UIImage(named: "bg1")
self.blurView.scrollView = table
self.blurView.setBlurLevel(6.0)
self.blurView.isGlassEffectOn = true
self.table.backgroundView = self.blurView
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// let height = CGFloat(scrollView.bounds.size.height)
// let position = max(scrollView.contentOffset.y, 0.0)
// let percent = min(position / height, 1.0)
// self.blurredBkgView.alpha = percent;
// print("scrollview bounds: \(scrollView.bounds)")
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// cell.backgroundView = self.blurView
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return unsortedCountryArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
cell.textLabel?.text = unsortedCountryArray[indexPath.row]
cell.textLabel?.textColor = UIColor.blueColor()
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This much code is blurring while scrolling.
To account for your content inset you need to change the frame you provide to your blurView
Eg
let contentInset = CGFloat(/*Your content inset*/)
let blurFrame = CGRect(x: 0, y: contentInset, width: tableView.frame.width, height: tableView.frame.height - contentInset)
self.blurView = DKLiveBlurView(frame: blurFrame)
EDIT: Old answer
You seem to be using bounds rather than frame for your DKLiveBlurView. This will cause you blur view to start from the top left of the screen (the origin of your view's frame)
Try:
self.blurView = DKLiveBlurView(frame: self.table.frame)
Rather than
self.blurView = DKLiveBlurView(frame: self.table.bounds)
I want to swipe each image to switch to another image like gallery app. I am now using this https://github.com/nicklockwood/SwipeView, but I don't know how to implement it. Should I drag a collection view inside my PhotoDetailViewController, or I only use it in coding. May anyone help me with this.
Here is my code:
import Foundation
import UIKit
import AAShareBubbles
import SwipeView
class PhotoDetailViewController: UIViewController, AAShareBubblesDelegate, SwipeViewDataSource, SwipeViewDelegate {
#IBOutlet var topView: UIView!
#IBOutlet var bottomView: UIView!
#IBOutlet var photoImageView: UIImageView!
var photoImage = UIImage()
var checkTapGestureRecognize = true
var swipeView: SwipeView = SwipeView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height))
override func viewDidLoad() {
title = "Photo Detail"
super.viewDidLoad()
photoImageView.image = photoImage
swipeView.dataSource = self
swipeView.delegate = self
let swipe = UISwipeGestureRecognizer(target: self, action: "swipeMethod")
swipeView.addGestureRecognizer(swipe)
swipeView.addSubview(photoImageView)
swipeView.pagingEnabled = false
swipeView.wrapEnabled = true
}
func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
return photoImageView
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SwipeCell", forIndexPath: indexPath) as! SwipeViewPhotoCell
return cell
}
#IBAction func onBackClicked(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
#IBAction func onTabGestureRecognize(sender: UITapGestureRecognizer) {
print("on tap")
if checkTapGestureRecognize == true {
bottomView.hidden = true
topView.hidden = true
self.navigationController?.navigationBarHidden = true
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
photoImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
checkTapGestureRecognize = false
showAminationOnAdvert()
}
else if checkTapGestureRecognize == false {
bottomView.hidden = false
topView.hidden = false
self.navigationController?.navigationBarHidden = false
checkTapGestureRecognize = true
}
}
func showAminationOnAdvert() {
let transitionAnimation = CATransition();
transitionAnimation.type = kCAEmitterBehaviorValueOverLife
transitionAnimation.subtype = kCAEmitterBehaviorValueOverLife
transitionAnimation.duration = 2.5
transitionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transitionAnimation.fillMode = kCAFillModeBoth
photoImageView.layer.addAnimation(transitionAnimation, forKey: "fadeAnimation")
}
#IBAction func onShareTouched(sender: AnyObject) {
print("share")
let myShare = "I am feeling *** today"
let shareVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)
self.presentViewController(shareVC, animated: true, completion: nil)
// print("share bubles")
// let shareBubles: AAShareBubbles = AAShareBubbles.init(centeredInWindowWithRadius: 100)
// shareBubles.delegate = self
// shareBubles.bubbleRadius = 40
// shareBubles.sizeToFit()
// //shareBubles.showFacebookBubble = true
// shareBubles.showTwitterBubble = true
// shareBubles.addCustomButtonWithIcon(UIImage(named: "twitter"), backgroundColor: UIColor.whiteColor(), andButtonId: 100)
// shareBubles.show()
}
#IBAction func playAutomaticPhotoImages(sender: AnyObject) {
animateImages(0)
}
func animateImages(no: Int) {
var number: Int = no
if number == images.count - 1 {
number = 0
}
let name: String = images[number]
self.photoImageView!.alpha = 0.5
self.photoImageView!.image = UIImage(named: name)
//code to animate bg with delay 2 and after completion it recursively calling animateImage method
UIView.animateWithDuration(2.0, delay: 0.8, options:UIViewAnimationOptions.CurveEaseInOut, animations: {() in
self.photoImageView!.alpha = 1.0;
},
completion: {(Bool) in
number++;
self.animateImages(number);
print(String(images[number]))
})
}
}
Just drag and drop a UIView to your storyboard/XIB, and set its customclass to SwipeView.
Also set the delegate and datasource to the view controller which includes the UIView you just dragged.
Then in the viewcontroller, implement the required delegate methods similar to how you'd implement the methods for a tableview.