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.
Related
I know this has been asked before but did could not figure-out how to achieve this in the shortest possible way in my case.
When I click on "Add" button (see GIF below), the animation function animates "imageView" (in this case the galaxy image) to fly to cart i.e. "notificationButton". Also "Add" button changes to "Remove" and button color changes from black to red (see GIF below). Fine with that.
Now, when I click the button for the second time i.e deselect it i.e. make it to default state, everything reverses, but the image still flies to the cart !
Now, I want to reverse the animation flying imageView animation to its original position when I push the button back to its default position second time, and again original flying animation, if the button is pushed again as many times as I want.
Though I have added complete ProductViewController code here but you skip everything and look at the last extension ProductViewController
I know this most likely has two steps -
i) Identifying that "buttonHandlerAddToCart" button is pressed second time i.e. from selected/isselected step to default step.
ii) Reversing the animation function "func animation" in ProductViewController.
How to go about it?
Relevant code:
SSBadgeButton:-
import UIKit
class SSBadgeButton: UIButton {
var badgeLabel = UILabel()
var badge: String? {
didSet {
addBadgeToButon(badge: badge)
}
}
public var badgeBackgroundColor = UIColor.red {
didSet {
badgeLabel.backgroundColor = badgeBackgroundColor
}
}
public var badgeTextColor = UIColor.white {
didSet {
badgeLabel.textColor = badgeTextColor
}
}
public var badgeFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
badgeLabel.font = badgeFont
}
}
public var badgeEdgeInsets: UIEdgeInsets? {
didSet {
addBadgeToButon(badge: badge)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addBadgeToButon(badge: nil)
}
func addBadgeToButon(badge: String?) {
badgeLabel.text = badge
badgeLabel.textColor = badgeTextColor
badgeLabel.backgroundColor = badgeBackgroundColor
badgeLabel.font = badgeFont
badgeLabel.sizeToFit()
badgeLabel.textAlignment = .center
let badgeSize = badgeLabel.frame.size
let height = max(18, Double(badgeSize.height) + 5.0)
let width = max(height, Double(badgeSize.width) + 10.0)
var vertical: Double?, horizontal: Double?
if let badgeInset = self.badgeEdgeInsets {
vertical = Double(badgeInset.top) - Double(badgeInset.bottom)
horizontal = Double(badgeInset.left) - Double(badgeInset.right)
let x = (Double(bounds.size.width) - 10 + horizontal!)
let y = -(Double(badgeSize.height) / 2) - 10 + vertical!
badgeLabel.frame = CGRect(x: x, y: y, width: width, height: height)
} else {
let x = self.frame.width - CGFloat((width / 2.0))
let y = CGFloat(-(height / 2.0))
badgeLabel.frame = CGRect(x: x, y: y, width: CGFloat(width), height: CGFloat(height))
}
badgeLabel.layer.cornerRadius = badgeLabel.frame.height/2
badgeLabel.layer.masksToBounds = true
addSubview(badgeLabel)
badgeLabel.isHidden = badge != nil ? false : true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addBadgeToButon(badge: nil)
fatalError("init(coder:) has not been implemented")
}
}
The ProductViewController code:
import UIKit
class ProductViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
let notificationButton = SSBadgeButton()
let rightbarbuttonimage = UIImage(named:"ic_cart")
fileprivate var cart = Cart()
let scrollView = UIScrollView()
let sections = ["Section A", "Section B","Section C", "Section D","Section E","Section F","Section G","Section H", "Section I","Section J","Section K","Section L"]
let rowspersection = [2,3,1,2,2,3,3,1,4,2,1,2]
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.tableView.backgroundColor = UIColor.gray
//Add and setup scroll view
self.tableView.addSubview(self.scrollView)
self.scrollView.translatesAutoresizingMaskIntoConstraints = false;
//Constrain scroll view
self.scrollView.leadingAnchor.constraint(equalTo: self.tableView.leadingAnchor, constant: 20).isActive = true;
self.scrollView.topAnchor.constraint(equalTo: self.tableView.topAnchor, constant: 20).isActive = true;
self.scrollView.trailingAnchor.constraint(equalTo: self.tableView.trailingAnchor, constant: -20).isActive = true;
self.scrollView.bottomAnchor.constraint(equalTo: self.tableView.bottomAnchor, constant: -20).isActive = true;
// customising rightBarButtonItems as notificationbutton
notificationButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
notificationButton.setImage(UIImage(named: "ic_cart")?.withRenderingMode(.alwaysTemplate), for: .normal)
notificationButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 15)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)
//following register is needed because I have rightbarbuttonitem customised as uibutton i.e. notificationbutton
notificationButton.addTarget(self, action: #selector(self.registerTapped(_:)), for: .touchUpInside)
}
#objc func registerTapped(_ sender: UIButton) {
self.performSegue(withIdentifier: "showCart", sender: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Workaround to avoid the fadout the right bar button item
self.navigationItem.rightBarButtonItem?.isEnabled = false
self.navigationItem.rightBarButtonItem?.isEnabled = true
//Update cart if some items quantity is equal to 0 and reload the product table and right button bar item
cart.updateCart()
//self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
notificationButton.badge = String(cart.items.count)// making badge equal to no.ofitems in cart
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// this segue to transfer data
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCart" {
if let cartViewController = segue.destination as? CartViewController {
cartViewController.cart = self.cart
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return productMap.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productMap[section]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let product = productMap[indexPath.section]![indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCell") as! ProductTableViewCell
cell.imageView?.image = product.imagename
cell.delegate = self as CartDelegate
cell.setButton(state: self.cart.contains(product: product))
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch(section) {
case 0: return "Section A"
case 1: return "Section B"
case 2: return "Section C"
case 3: return "Section D"
case 4: return "Section E"
case 5: return "Section F"
case 6: return "Section G"
case 7: return "Section H"
case 8: return "Section I"
case 9: return "Section J"
case 10: return "Section K"
case 11: return "Section L"
default: return ""
}
}
}
extension ProductViewController: CartDelegate {
// MARK: - CartDelegate
func updateCart(cell: ProductTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let product = productMap[indexPath.section]![indexPath.row]
//Update Cart with product
cart.updateCart(with: product)
// self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
notificationButton.badge = String(cart.items.count) // making badge equal to noofitems in cart
}
}
***// Most relevant code begins here -***
extension ProductViewController {
#IBAction func buttonHandlerAddToCart(_ sender: UIButton) {
let buttonPosition : CGPoint = sender.convert(sender.bounds.origin, to: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: buttonPosition)!
let cell = tableView.cellForRow(at: indexPath) as! ProductTableViewCell
let imageViewPosition : CGPoint = cell.imageView!.convert(cell.imageView!.bounds.origin, to: self.view)
let imgViewTemp = UIImageView(frame: CGRect(x: imageViewPosition.x, y: imageViewPosition.y, width: cell.imageView!.frame.size.width, height: cell.imageView!.frame.size.height))
imgViewTemp.image = cell.imageView!.image
animation(tempView: imgViewTemp)
}
func animation(tempView : UIView) {
self.view.addSubview(tempView)
UIView.animate(
withDuration: 1.0,
animations: {
tempView.animationZoom(scaleX: 1.5, y: 1.5)
}, completion: { _ in
UIView.animate(withDuration: 0.5, animations: {
tempView.animationZoom(scaleX: 0.2, y: 0.2)
tempView.animationRoted(angle: CGFloat(Double.pi))
tempView.frame.origin.x = self.notificationButton.frame.origin.x
tempView.frame.origin.y = self.notificationButton.frame.origin.y
}, completion: { _ in
tempView.removeFromSuperview()
UIView.animate(withDuration: 1.0, animations: {
self.notificationButton.animationZoom(scaleX: 1.4, y: 1.4)
}, completion: {_ in
self.notificationButton.animationZoom(scaleX: 1.0, y: 1.0)
})
})
}
)
}
}
extension UIView{
func animationZoom(scaleX: CGFloat, y: CGFloat) {
self.transform = CGAffineTransform(scaleX: scaleX, y: y)
}
func animationRoted(angle : CGFloat) {
self.transform = self.transform.rotated(by: angle)
}
}
I have also included ProductTableViewCell code, just in case:
import UIKit
protocol CartDelegate {
func updateCart(cell: ProductTableViewCell)
}
class ProductTableViewCell: UITableViewCell {
weak var myParent:ProductViewController?
#IBOutlet weak var imagename: UIImageView!
#IBOutlet weak var addToCartButton: UIButton!
var delegate: CartDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
addToCartButton.layer.cornerRadius = 5
addToCartButton.clipsToBounds = true
}
func setButton(state: Bool) {
addToCartButton.isUserInteractionEnabled = true
addToCartButton.isSelected = state
addToCartButton.backgroundColor = (!addToCartButton.isSelected) ? .blue : .red
}
#IBAction func addToCart(_ sender: Any) {
setButton(state: !addToCartButton.isSelected)
self.delegate?.updateCart(cell: self)
}
}
Edit: on #aheze's request :
struct Product: Equatable {
let imagename: UIImage
}
var productMap = [
0: [ Product(imagename:#imageLiteral(resourceName: "blue")), Product( imagename:#imageLiteral(resourceName: "CakeImage")) ]
1: [ Product(imagename:#imageLiteral(resourceName: "vectorlogo")), Product(imagename:#imageLiteral(resourceName: "PeasImge")), Product(imagename:#imageLiteral(resourceName: "castle"))],
2: [ Product( imagename:#imageLiteral(resourceName: "scoobydoo")),Product(imagename:#imageLiteral(resourceName: "ufo"))] ,
3: [ Product( imagename:#imageLiteral(resourceName: "wolfsky")),Product( imagename:#imageLiteral(resourceName: "universe")) ],
4: [ Product(imagename:#imageLiteral(resourceName: "werewolf")),Product( imagename:#imageLiteral(resourceName: "galaxy")) ]
]
Edit 2: class Cart, on #aheze's request:
import Foundation
class Cart {
var items : [CartItem] = []
}
extension Cart {
var totalQuantity : Int {
get { return items.reduce(0) { value, item in
value + item.quantity
}
}
}
func updateCart(with product: Product) {
if !self.contains(product: product) {
self.add(product: product)
} else {
self.remove(product: product)
}
}
func updateCart() {
for item in self.items {
if item.quantity == 0 {
updateCart(with: item.product)
}
}
}
func add(product: Product) {
let item = items.filter { $0.product == product }
if item.first != nil {
item.first!.quantity += 1
} else {
items.append(CartItem(product: product))
}
}
func remove(product: Product) {
guard let index = items.firstIndex(where: { $0.product == product }) else { return}
items.remove(at: index)
}
func contains(product: Product) -> Bool {
let item = items.filter { $0.product == product }
return item.first != nil
}
}
Further information you need, feel free...
Does this work? (the gif was too big)
https://imgur.com/a/jrcwEWv
I made separate functions for adding and removing from the cart.
extension ProductViewController: CartDelegate {
// MARK: - CartDelegate
func updateCart(cell: ProductTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let product = productMap[indexPath.section]![indexPath.row]
/// `var selectedIndexPaths = [IndexPath]()` defined inside `ProductViewController`, to keep track of the selected products
if selectedIndexPaths.contains(indexPath) {
if let index = selectedIndexPaths.firstIndex(of: indexPath) {
selectedIndexPaths.remove(at: index)
removeProductFromCart(indexPath: indexPath)
}
} else {
selectedIndexPaths.append(indexPath)
addProductToCart(indexPath: indexPath)
}
// addProductToCart(indexPath: indexPath)
/// **I commented this out because I don't have the code for `Cart`**
//Update Cart with product
// cart.updateCart(with: product)
// self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
// notificationButton.badge = String(cart.items.count) // making badge equal to noofitems in cart
}
}
func addProductToCart(indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
if let imageView = cell.imagename {
let initialImageViewFrame = imageView.convert(imageView.frame, to: self.view)
let targetImageViewFrame = self.notificationButton.frame
let imgViewTemp = UIImageView(frame: initialImageViewFrame)
imgViewTemp.clipsToBounds = true
imgViewTemp.contentMode = .scaleAspectFill
imgViewTemp.image = imageView.image
self.view.addSubview(imgViewTemp)
UIView.animate(withDuration: 1.0, animations: {
imgViewTemp.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}) { _ in
UIView.animate(withDuration: 0.5, animations: {
imgViewTemp.transform = CGAffineTransform(scaleX: 0.2, y: 0.2).rotated(by: CGFloat(Double.pi))
imgViewTemp.frame = targetImageViewFrame
}) { _ in
imgViewTemp.removeFromSuperview()
UIView.animate(withDuration: 1.0, animations: {
self.notificationButton.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
}, completion: {_ in
self.notificationButton.transform = CGAffineTransform.identity
})
}
}
}
}
}
func removeProductFromCart(indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
if let imageView = cell.imagename {
let initialImageViewFrame = self.notificationButton.frame
let targetImageViewFrame = imageView.convert(imageView.frame, to: self.view)
let imgViewTemp = UIImageView(frame: initialImageViewFrame)
imgViewTemp.clipsToBounds = true
imgViewTemp.contentMode = .scaleAspectFill
imgViewTemp.image = imageView.image
self.view.addSubview(imgViewTemp)
var initialTransform = CGAffineTransform.identity
initialTransform = initialTransform.scaledBy(x: 0.2, y: 0.2)
initialTransform = initialTransform.rotated(by: CGFloat(Double.pi))
UIView.animate(withDuration: 0.5, animations: {
self.notificationButton.animationZoom(scaleX: 1.4, y: 1.4)
imgViewTemp.transform = initialTransform
}) { _ in
UIView.animate(withDuration: 1, animations: {
self.notificationButton.animationZoom(scaleX: 1, y: 1)
imgViewTemp.transform = CGAffineTransform.identity
imgViewTemp.frame = targetImageViewFrame
}) { _ in
imgViewTemp.removeFromSuperview()
}
}
}
}
}
Some things that you should fix:
Instead of using imagename (the image view that you added to your table view cell), you used cell.imageView! which is the built-in image view that all cells have. Don't use this.
Inside ProductTableViewCell, you should make a separate property for keeping track of selected/not selected state instead of using UIButton's isSelected. This way, you won't run into unwanted behavior when changing the button color (currently, a red rectangle will appear behind the button's text for a moment)
If you're combining transforms, you should do this:
var initialTransform = CGAffineTransform.identity
initialTransform = initialTransform.scaledBy(x: 0.2, y: 0.2)
initialTransform = initialTransform.rotated(by: CGFloat(Double.pi))
tempView.transform = initialTransform
instead of:
tempView.animationZoom(scaleX: 0.2, y: 0.2)
tempView.animationRoted(angle: CGFloat(Double.pi))
Here's the full project (added some more comments too).
I have these two classes which are for having the custom tapbar, I would like to use them in swiftUI how can I do? I used these wrappers but once implemented the class in the ContentView does not appear to me
I would like to do everything in swiftUI so I would prefer not to use storyboards in the implementation. it's possible ?
//SwiftUI class. I want to use this view already done in SwiftUI
HStack {
SHCircleBarControllerView()
SHCircleBarView()
}
//Class Swift 4
import UIKit
import SwiftUI
struct SHCircleBarControllerView : UIViewControllerRepresentable {
typealias UIViewControllerType = SHCircleBarController
func makeCoordinator() -> SHCircleBarControllerView.Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<SHCircleBarControllerView>) -> SHCircleBarController {
return SHCircleBarController()
}
func updateUIViewController(_ uiViewController: SHCircleBarController, context: UIViewControllerRepresentableContext<SHCircleBarControllerView>) {
}
class Coordinator : NSObject {
var parent : SHCircleBarControllerView
init(_ viewController : SHCircleBarControllerView){
self.parent = viewController
}
}
}
class SHCircleBarController: UITabBarController {
fileprivate var shouldSelectOnTabBar = true
private var circleView : UIView!
private var circleImageView: UIImageView!
open override var selectedViewController: UIViewController? {
willSet {
guard shouldSelectOnTabBar, let newValue = newValue else {
shouldSelectOnTabBar = true
return
}
guard let tabBar = tabBar as? SHCircleBar, let index = viewControllers?.firstIndex(of: newValue) else {return}
tabBar.select(itemAt: index, animated: true)
}
}
open override var selectedIndex: Int {
willSet {
guard shouldSelectOnTabBar else {
shouldSelectOnTabBar = true
return
}
guard let tabBar = tabBar as? SHCircleBar else {
return
}
tabBar.select(itemAt: selectedIndex, animated: true)
}
}
open override func viewDidLoad() {
super.viewDidLoad()
let tabBar = SHCircleBar()
self.setValue(tabBar, forKey: "tabBar")
self.circleView = UIView(frame: .zero)
circleView.layer.cornerRadius = 30
circleView.backgroundColor = .white
circleView.isUserInteractionEnabled = false
self.circleImageView = UIImageView(frame: .zero)
circleImageView.layer.cornerRadius = 30
circleImageView.isUserInteractionEnabled = false
circleImageView.contentMode = .center
circleView.addSubview(circleImageView)
self.view.addSubview(circleView)
let tabWidth = self.view.bounds.width / CGFloat(self.tabBar.items?.count ?? 4)
circleView.frame = CGRect(x: tabWidth / 2 - 30, y: self.tabBar.frame.origin.y - 40, width: 60, height: 60)
circleImageView.frame = self.circleView.bounds
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
circleImageView.image = image(with: self.tabBar.selectedItem?.image ?? self.tabBar.items?.first?.image, scaledTo: CGSize(width: 30, height: 30))
}
private var _barHeight: CGFloat = 74
open var barHeight: CGFloat {
get {
if #available(iOS 11.0, *) {
return _barHeight + view.safeAreaInsets.bottom
} else {
return _barHeight
}
}
set {
_barHeight = newValue
updateTabBarFrame()
}
}
private func updateTabBarFrame() {
var tabFrame = self.tabBar.frame
tabFrame.size.height = barHeight
tabFrame.origin.y = self.view.frame.size.height - barHeight
self.tabBar.frame = tabFrame
tabBar.setNeedsLayout()
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateTabBarFrame()
}
open override func viewSafeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.viewSafeAreaInsetsDidChange()
}
updateTabBarFrame()
}
open override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let idx = tabBar.items?.firstIndex(of: item) else { return }
if idx != selectedIndex, let controller = viewControllers?[idx] {
shouldSelectOnTabBar = false
selectedIndex = idx
let tabWidth = self.view.bounds.width / CGFloat(self.tabBar.items!.count)
UIView.animate(withDuration: 0.3) {
self.circleView.frame = CGRect(x: (tabWidth * CGFloat(idx) + tabWidth / 2 - 30), y: self.tabBar.frame.origin.y - 15, width: 60, height: 60)
}
UIView.animate(withDuration: 0.15, animations: {
self.circleImageView.alpha = 0
}) { (_) in
self.circleImageView.image = self.image(with: item.image, scaledTo: CGSize(width: 30, height: 30))
UIView.animate(withDuration: 0.15, animations: {
self.circleImageView.alpha = 1
})
}
delegate?.tabBarController?(self, didSelect: controller)
}
}
private func image(with image: UIImage?, scaledTo newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, _: false, _: 0.0)
image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
You can set up your custom UIViewControllers inside the SHCircleBarController through the viewControllers property.
In SHCircleBarController
open override func viewDidLoad() {
super.viewDidLoad()
...
viewControllers = [ViewController(), ViewController2()]
}
Your other UIViewControllers
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
}
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blue
}
}
This is the result
I have collection view with Images of photo library But there is a problem just for first time that user Allows using photos - when the app runs for the first time and user allows to use photos the user can't see anyImages and should dismiss that view controller and come back again to see the Images
here is the codes :
import UIKit
import Photos
class typeandtranslateViewController: UIViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate , UICollectionViewDelegate, UICollectionViewDataSource , UITextFieldDelegate {
static var checkTextField = Bool()
#IBOutlet var backgroundimg: UIImageView!
#IBOutlet var frontimg: UIImageView!
#IBOutlet weak var typeView: UIView!
let arr_img = NSMutableArray()
let arr_selected = NSMutableArray()
#IBOutlet var collview: UICollectionView!
#IBOutlet weak var sefareshTitleTextField: UITextField!
#IBAction func caneraButton(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera ;
imagePicker.allowsEditing = false
self.present(imagePicker,animated: true , completion: nil)
}
print("Camera!")
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
UIImageWriteToSavedPhotosAlbum(selectedImage,self,nil,nil)
dismiss(animated: true, completion: nil)
print("save Image ")
}
#IBOutlet weak var viewCamera: UIView!
override func viewDidLoad() {
super.viewDidLoad()
print("Text Field Condition ")
if sefareshTitleTextField!.text! == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
self.sefareshTitleTextField.delegate = self
collview?.allowsMultipleSelection = true
let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
allPhotosResult.enumerateObjects({ (asset, idx, stop) in
self.arr_img.add(asset)
})
self.typeView.layer.cornerRadius = self.typeView.frame.size.height/50
self.typeView.layer.borderWidth = 1
self.typeView.layer.borderColor = UIColor.clear.cgColor
self.typeView.clipsToBounds = true
self.viewCamera.layer.cornerRadius = 5
self.viewCamera.layer.borderWidth = 1
self.viewCamera.layer.borderColor = UIColor.clear.cgColor
self.viewCamera.clipsToBounds = true
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = CGRect(x: self.backgroundimg.frame.origin.x, y: self.backgroundimg.frame.origin.y, width: self.backgroundimg.frame.size.width, height: self.backgroundimg.frame.size.height)
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.backgroundimg.addSubview(blurView)
}
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
let retinaScale = UIScreen.main.scale
let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
var thumbnail = UIImage()
options.isSynchronous = true
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
options.normalizedCropRect = cropRect
manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
if sefareshTitleTextField!.text == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
return false;
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if sefareshTitleTextField!.text! == "" {
typeandtranslateViewController.checkTextField = false
print("sefaresh title is nill")
} else if sefareshTitleTextField!.text! != "" {
typeandtranslateViewController.checkTextField = true
print("sefaresh title isnt nill")
}
}
//MARK:
//MARK: Collectioview methods
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return arr_img.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celll",
for: indexPath)
let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)
let selectView : UIImageView = cell.viewWithTag(22) as! UIImageView
if arr_selected.contains(indexPath.row){
selectView.image = UIImage(named: "Select.png")
}else{
selectView.image = UIImage(named: "radioCircleButton.png")
}
cell.layer.cornerRadius = 5
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.clear.cgColor
cell.clipsToBounds = true
return cell
}
var selectedIndexes = [NSIndexPath]() {
didSet {
collview.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
if arr_selected.contains(indexPath.row){
arr_selected.remove(indexPath.row)
}else{
arr_selected.add(indexPath.row)
}
self.collview.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = backgroundimg.bounds
backgroundimg.addSubview(blurView)
backgroundimg.frame = self.view.bounds
}
#IBAction func backToTheMainCustom(_ sender: UIButton) {
performSegue(withIdentifier: "backToTheMainCustom", sender: self)
sefareshTitleTextField!.text! = ""
typeandtranslateViewController.checkTextField = false
}
}
First you need to ask user for permissions to access to the photo library. If request happens first time, wait for his answer and open the UIImagePickerController again. Please review the following code:
let photosAccess = PHPhotoLibrary.authorizationStatus()
switch photosAccess {
case .notDetermined:
// First time here. Request the access
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
// Access was just granted
// Open library here
}
})
case .authorized:
// Open library here
case .denied, .restricted:
// Photos access is not granted.
// Good place to take user to app settings.
}
The same about camera:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { response in
if response {
DispatchQueue.main.async {
// Show camera UI here
}
} else {
DispatchQueue.main.async {
// Access is restricred
}
}
}
I have a SearchViewController, and as part of this ViewController I have a UISearchController (with a SearchResultsController called SearchResultsTableViewController). I notice that my SearchResultsTableViewController's UITableView contentInset.top is 20 points more than it should be, despite it being fine on iOS8/9 and having automaticallyAdjustScrollViewInsets = true. If I perform a segue from this ViewController to another, then go back, I see that the contentInset.top increases another 20 points. Again, this does not occur on iOS8/9. Here are a couple of images showing this behavior.
Here is the code for the two relevant ViewControllers.
class SearchViewController: UIViewController, UISearchBarDelegate, UISearchControllerDelegate {
#IBOutlet var tableView: UITableView!
#IBOutlet var backgroundImageView: UIImageView!
var searchController: UISearchController!
var backBarButtonItem: UIBarButtonItem!
var searchButtonTapped = false
#IBOutlet var titleLabel: SpringLabel!
#IBOutlet var loadingIndicatorView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let searchResultsVC = self.storyboard!.instantiateViewController(withIdentifier: "SearchResultsTableViewController") as! SearchResultsTableViewController
searchResultsVC.searchController = self
searchController = UISearchController(searchResultsController: searchResultsVC)
searchController.searchResultsUpdater = searchResultsVC
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = true
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = "Search Courses"
searchController.view.backgroundColor = UIColor.clear
searchController.searchBar.keyboardAppearance = .dark
self.setSearchBarCaretColor(UIColor(red: 0.24, green: 0.34, blue: 0.19, alpha: 1.0))
self.setSearchBarFontSize(17.0)
self.navigationItem.titleView = searchController.searchBar
self.definesPresentationContext = true
self.backBarButtonItem = self.navigationItem.leftBarButtonItem
self.backgroundImageView.clipsToBounds = true
self.titleLabel.alpha = 0
self.titleLabel.layer.shadowColor = UIColor.black.cgColor
self.titleLabel.layer.shadowOpacity = 0.8
self.titleLabel.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
self.titleLabel.layer.shouldRasterize = true
self.titleLabel.layer.rasterizationScale = UIScreen.main.scale
self.loadingIndicatorView.layer.zPosition = CGFloat.greatestFiniteMagnitude
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.perform(#selector(SearchViewController.showKeyboard), with: nil, afterDelay: 0.01)
searchBarTextDidBeginEditing(searchController.searchBar)
}
func showKeyboard() {
self.searchController.searchBar.becomeFirstResponder()
}
func hideKeyboard() {
self.searchController.searchBar.resignFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.titleLabel.delay = 0.1
self.titleLabel.animation = "zoomIn"
self.titleLabel.duration = 0.6
self.titleLabel.animate()
let selectedRowIndexPath = self.tableView.indexPathForSelectedRow
if ((selectedRowIndexPath) != nil) {
self.tableView.deselectRow(at: selectedRowIndexPath!, animated: true)
self.transitionCoordinator?.notifyWhenInteractionEnds({ context in
if (context.isCancelled) {
self.tableView.selectRow(at: selectedRowIndexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
}
})
}
}
func setSearchBarCaretColor(_ color : UIColor) {
let view = searchController.searchBar.subviews[0]
let subViewsArray = view.subviews
for subView in subViewsArray {
if subView.isKind(of: UITextField.self) {
subView.tintColor = color
}
}
}
func setSearchBarFontSize(_ pointSize : CGFloat) {
let view = searchController.searchBar.subviews[0]
let subViewsArray = view.subviews
for subView in subViewsArray {
if subView.isKind(of: UITextField.self) {
let textField = subView as! UITextField
textField.font = UIFont.systemFont(ofSize: pointSize)
}
}
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
//This doesn't animate for some reason, so don't use it.
if (UI_USER_INTERFACE_IDIOM() != .pad) { //Because the iPad (for some reason) doesn't ever show the Cancel button, so keep the back button.
UIView.animate(withDuration: 0.3, animations: { self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView()) }, completion: { Void in
self.navigationItem.setHidesBackButton(true, animated: false)
})
}
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
if (self.searchButtonTapped == false) {
self.navigationItem.leftBarButtonItem = self.backBarButtonItem
self.navigationItem.setHidesBackButton(false, animated: true)
} else {
self.searchButtonTapped = false
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.navigationItem.leftBarButtonItem = self.backBarButtonItem
self.navigationItem.setHidesBackButton(false, animated: true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchButtonTapped = true
searchBar.resignFirstResponder()
}
}
Now here is SearchResultsTableViewController:
class SearchResultsTableViewController: UITableViewController, UISearchResultsUpdating {
var resultsArray = [CourseResult]()
var emptySearchResultsView : EmptySearchResultsView!
var keyboardActive = false
var keyboardHeight : CGFloat = 0.0
var searchController : SearchViewController!
var query = PFQuery(className: "Course")
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor.clear
self.tableView.estimatedRowHeight = 140
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.keyboardDismissMode = .onDrag
self.emptySearchResultsView = EmptySearchResultsView.construct(self) as EmptySearchResultsView
emptySearchResultsView.translatesAutoresizingMaskIntoConstraints = true
self.emptySearchResultsView.isHidden = true
self.tableView.addSubview(emptySearchResultsView)
query.whereKey("institution", equalTo: "College")
query.limit = 20
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.registerKeyboardNotifications()
let selectedRowIndexPath = self.tableView.indexPathForSelectedRow
if ((selectedRowIndexPath) != nil) {
self.tableView.deselectRow(at: selectedRowIndexPath!, animated: true)
self.transitionCoordinator?.notifyWhenInteractionEnds({ context in
if (context.isCancelled) {
self.tableView.selectRow(at: selectedRowIndexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
}
})
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.unregisterKeyboardNotifications()
}
var lastSearch = ""
func updateSearchResults(for searchController: UISearchController) {
guard searchController.isActive else { return }
if (lastSearch == searchController.searchBar.text!) {
return
}
self.lastSearch = searchController.searchBar.text!
query.cancel()
self.emptySearchResultsView.isHidden = true
if (searchController.searchBar.text?.characters.count == 0) {
resultsArray.removeAll()
self.tableView.reloadData()
}
if ((searchController.searchBar.text?.characters.count)! > 0) {
self.searchController.loadingIndicatorView.startAnimating()
var searchString = searchController.searchBar.text!
searchString = searchString.lowercased()
var searchStringArray = searchString.components(separatedBy: " ")
searchStringArray = searchStringArray.filter { $0 != "" }
//print(searchStringArray.description)
query.whereKey("searchTerms", containsAllObjectsIn: searchStringArray)
query.findObjectsInBackground(block: { (results, error) -> Void in
if (error == nil) {
self.resultsArray = []
let courseResultsArray = results! as [PFObject]
for result in courseResultsArray {
//removed all of this jargon.
}
self.searchController.loadingIndicatorView.stopAnimating()
self.tableView.reloadData()
if (self.resultsArray.count == 0) {
self.emptySearchResultsView.isHidden = false
} else {
self.emptySearchResultsView.isHidden = true
}
} else {
print(error?.localizedDescription)
self.searchController.loadingIndicatorView.stopAnimating()
}
})
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if (self.keyboardActive == true) {
self.emptySearchResultsView.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.tableView.bounds.height - self.keyboardHeight - self.tableView.contentInset.top)
self.emptySearchResultsView.setNeedsLayout()
} else {
self.emptySearchResultsView.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.tableView.bounds.height - self.tableView.contentInset.top)
self.emptySearchResultsView.setNeedsLayout()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellContent: CourseResult = self.resultsArray[(indexPath as NSIndexPath).row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CourseResultTableViewCell", for: indexPath) as! CourseResultTableViewCell
cell.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
cell.backgroundColor = UIColor.clear
cell.courseLabel.text = cellContent.courseCode + " - " + cellContent.courseName
cell.universityLabel.text = cellContent.university
cell.facultyLabel.text = cellContent.faculty
cell.leftHandSideImageView.image = UIImage(named: cellContent.faculty)
cell.leftHandSideImageView.layer.shadowColor = UIColor.black.cgColor
cell.leftHandSideImageView.layer.shadowOpacity = 0.6
cell.leftHandSideImageView.layer.shouldRasterize = true
cell.leftHandSideImageView.layer.rasterizationScale = UIScreen.main.scale
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let schedulesVC = self.storyboard!.instantiateViewController(withIdentifier: "SchedulesViewController") as! SchedulesViewController
schedulesVC.selectedCourse = self.resultsArray[(indexPath as NSIndexPath).row]
self.searchController.show(schedulesVC, sender: tableView)
}
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(SearchResultsTableViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SearchResultsTableViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification: Notification) {
if (UI_USER_INTERFACE_IDIOM() != .phone) { //Because devices like iPads don't have they keyboards affect the error screen visibility much.
return
}
if let keyboardFrame = ((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue {
UIView.animate(withDuration: 0.6, animations: { self.emptySearchResultsView.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.tableView.bounds.height - keyboardFrame.height - self.tableView.contentInset.top)
self.emptySearchResultsView.layoutIfNeeded()
})
self.keyboardActive = true
self.keyboardHeight = keyboardFrame.height
}
}
func keyboardWillHide(_ notification: Notification) {
if (UI_USER_INTERFACE_IDIOM() != .phone) {
return
}
UIView.animate(withDuration: 0.6, animations: { self.emptySearchResultsView.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.tableView.bounds.height - self.tableView.contentInset.top)
self.emptySearchResultsView.layoutIfNeeded()
})
self.keyboardActive = false
}
}
Each of these ViewControllers have their own representation in the storyboard.
Does anyone have an idea why I see this behavior, which is only seen in iOS10? The issue occurs on a wide range of devices from what I have tested.
Note: Just ignore any string parsing code related to the results or any other related code. I removed some of this stuff to try to make the code a little more coherent, along with json parsing code, etc
The only solution that has worked for me (which is not ideal) is to check if the device is running iOS10 and to dynamically adjust the contentInset.top based on the height of the status bar and navigationBar. Obviously I had to turn off automaticallyAdjustScrollViewInsets to do this.
How to use protocol? I can't use it. I just wanna print out "abc" when I click the start button. It didn't work. plz help me
import UIKit
import SpriteKit
protocol GameDelegate {
func gameOver()
}
class MainMenuScene: SKScene
{
var Gdelegate: GameDelegate?
override func didMoveToView(view: SKView)
{
let background = SKSpriteNode(imageNamed: "DiscsBackground")
background.size = self.size
background.zPosition = 0
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
self.addChild(background)
let gameTitleLabel1 = SKLabelNode(fontNamed: "Pusab")
gameTitleLabel1.text = "Disappearing"
gameTitleLabel1.fontSize = 90
gameTitleLabel1.fontColor = SKColor.whiteColor()
gameTitleLabel1.position = CGPoint(x: self.size.width/2, y: self.size.height*0.75)
gameTitleLabel1.zPosition = 1
self.addChild(gameTitleLabel1)
let gameTitleLabel2 = SKLabelNode(fontNamed: "Pusab")
gameTitleLabel2.text = "Discs"
gameTitleLabel2.fontSize = 250
gameTitleLabel2.fontColor = SKColor.whiteColor()
gameTitleLabel2.position = CGPoint(x: self.size.width/2, y: self.size.height*0.6)
gameTitleLabel2.zPosition = 1
self.addChild(gameTitleLabel2)
let gameByLabel = SKLabelNode(fontNamed: "Pusab")
gameByLabel.text = "Disappearing"
gameByLabel.fontSize = 90
gameByLabel.fontColor = SKColor.whiteColor()
gameTitleLabel2.position = CGPoint(x: self.size.width/2, y: self.size.height*0.95)
gameByLabel.zPosition = 1
self.addChild(gameByLabel)
let startLabel = SKLabelNode(fontNamed: "Pusab")
startLabel.text = "start"
startLabel.fontSize = 150
startLabel.fontColor = SKColor.whiteColor()
startLabel.position = CGPoint(x: self.size.width/2, y: self.size.height*0.35)
startLabel.zPosition = 1
startLabel.name = "startButton"
self.addChild(startLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
for touch: AnyObject in touches
{
let pointOfTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointOfTouch)
let tappedNodeName = tappedNode.name
if tappedNodeName == "startButton"
{
//self.scene?.view?.presentScene(nil)
Gdelegate?.gameOver()
}
}
}
}
class MHAGameViewController: UIViewController,GameDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let scene = MainMenuScene(size: CGSize(width: 1536, height: 2048))
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
func gameOver() {/*
self.performSegueWithIdentifier("segue1", sender: self)
let alertController = UIAlertController(title: "HELP", message:
"Please wait....", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "close", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)*/
print("abc")
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
You should set the delegate as follow :
let scene = MainMenuScene(size: CGSize(width: 1536, height: 2048))
scene.Gdelegate = self
Step: 1 - Declare protocol Just before class Declaration and Below Import stmt. (Inside Cell Class)
protocol BtnsAction: NSObjectProtocol
{
func btnLearnAction(_ sender: Any?)
}
weak var delegate: BtnsAction?
Step: 2 - Declare Button Action Method inside Cell Class.
#IBAction func btnLearnMoreAction(_ sender: UIButton) {
self.delegate?.btnLearnAction(self)
}
Step: 3 - Now, Inside ViewController.
class MyViewController_VC:ViewController, BtnsAction
//MARK: - Protocol Method -
func btnLearnAction(_ sender: Any?) {
let cell = sender as! SubCategoryCell
let indexpath = self.TableView1.indexPath(for: cell)
let dictData = self.arrFree_Listing[(indexpath?.row)!] as! NSMutableDictionary
let strId = String(dictData.value(forKey: "id") as! Int)
let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "ListingDetails_InnerVC") as! ListingDetails_InnerVC
detailVC.strID = strId
self.navigationController?.pushViewController(detailVC, animated: true)
}
**Don't Forget to add **
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "_Cell") as! _Cell
cell.delegate = self
return cell
}