UITableViewCell constraints not updated till I scroll tableview - ios

Following is my code to update view height inside tableview cell
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
fileprivate func layout() {
rootFlexContainer.frame.size.width = frame.width - 20
rootFlexContainer.flex.layout(mode: .adjustHeight)
if(rootFlexContainer.frame.height != 0) {
tagsHeight.constant = rootFlexContainer.frame.height
}
}
although this is not reflected till I scroll i.e is cell is recreated. How to update constraint inside TableViewCell of a view?
here is entire tableviewcell code
import UIKit
import FlexLayout
import SDWebImage
class StoreListTableViewCell: UITableViewCell {
#IBOutlet weak var menuLbl: UILabel!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var cellBgview: UIView!
#IBOutlet weak var storeImg: UIImageView!
#IBOutlet weak var storeLocation: UILabel!
#IBOutlet weak var storeTitle: UILabel!
#IBOutlet weak var cellContainer: UIView!
#IBOutlet weak var stackView: UIStackView!
#IBOutlet weak var tagsHeight: NSLayoutConstraint!
var storeImgStr = ""
var storeTitleStr = ""
var storeLocationStr = ""
var score : Double = 0.0
var tagsStr = ""
var isMenuAvailble = 0
var retailerTags: [String]?
var cashbackString = ""
fileprivate let rootFlexContainer = UIView()
#IBOutlet weak var tagsView: UIView!
#IBOutlet weak var ratingBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.layoutIfNeeded()
cellBgview.clipsToBounds = true
cellBgview.layer.cornerRadius = 5
cellContainer.layer.shadowColor = UIColor.lightGray.cgColor
cellContainer.layer.shadowOpacity = 0.5
cellContainer.layer.shadowRadius = 5.0
cellContainer.layer.shadowOffset = CGSize(width: 0, height: 2)
cellContainer.backgroundColor = UIColor.clear
cellContainer.layer.cornerRadius = 5.0
cellContainer.layer.borderColor = UIColor.white.cgColor
cellContainer.layer.borderWidth = 0.5
ratingBtn.layer.borderWidth = 1
ratingBtn.layer.cornerRadius = 5
tagsView.addSubview(rootFlexContainer)
//cellContainer.layer.shadowPath = UIBezierPath(rect: cellBgview.bounds).cgPath
}
func setSetupStoreUI() {
if isMenuAvailble == 1 {
menuView.isHidden = false
menuView.layer.cornerRadius = 10
} else {
menuView.isHidden = true
}
storeTitle.text = storeTitleStr
// storeTitle.sizeToFit()
storeLocation.text = storeLocationStr
//storeLocation.sizeToFit()
//.filter{ $0.name != " " }
//storeImg.sd_imageIndicator = SDWebImageActivityIndicator.gray
storeImg.backgroundColor = UIColor.hexStringToUIColor(hex: AppStrings.placeHolderColor)
if let url = URL(string: storeImgStr.encoded), !(storeImgStr.isEmpty) {
self.storeImg.sd_setImage(with: url)
}
menuLbl.text = AppLocalString.PREORDER_TEXT.localized()
menuLbl.font = FontStyle.ProximaNovaBold(size: 12)
storeTitle.font = FontStyle.ProximaNovaSemibold(size: 14)
storeLocation.font = FontStyle.ProximaNovaRegular(size: 12)
storeLocation.textColor = .gray
// ratingBtn.isHidden = (score == 0)
ratingBtn.setTitle(score == 0 ? "-" : String(format: "%.1f", score), for: .normal)
ratingBtn.backgroundColor = UIColor.hexStringToUIColor(hex: Utility.getRatingColor(rating: score))
ratingBtn.layer.borderColor = UIColor.hexStringToUIColor(hex: Utility.getRatingColor(rating: score)).cgColor
rootFlexContainer.subviews.forEach({ $0.removeFromSuperview() })
//tagsView.willRemoveSubview(rootFlexContainer)
//rootFlexContainer.frame = tagsView.frame
//tagsView.addSubview(rootFlexContainer)
rootFlexContainer.flex.direction(.row).wrap(.wrap).alignSelf(.auto).justifyContent(.start).paddingRight(2).define { (flex) in
for i in 0..<((retailerTags?.count ?? 0) > 3 ? 3 : (retailerTags?.count ?? 0)) {
let nameLabel = UIButton()
nameLabel.isUserInteractionEnabled = false
nameLabel.setTitle((retailerTags?[i] ?? "").trim(), for: .normal)
nameLabel.setTitleColor(.black, for: .normal)
nameLabel.titleLabel?.font = FontStyle.ProximaNovaRegular(size: 11)
nameLabel.contentEdgeInsets = UIEdgeInsets(top: 1.5, left: 4, bottom: 1.5, right:4)
nameLabel.layer.borderColor = UIColor.hexStringToUIColor(hex: AppStrings.grayBorderColor).cgColor
nameLabel.layer.cornerRadius = 8
nameLabel.layer.borderWidth = 1.0
nameLabel.sizeToFit()
flex.addItem(nameLabel).margin(2)
}
if cashbackString != "" {
let cashbackLabel = UIButton()
cashbackLabel.backgroundColor = UIColor.hexStringToUIColor(hex: AppStrings.orangeCashbackColor)
cashbackLabel.isUserInteractionEnabled = false
cashbackLabel.setTitle(cashbackString, for: .normal)
cashbackLabel.setTitleColor(.black, for: .normal)
cashbackLabel.titleLabel?.font = FontStyle.ProximaNovaRegular(size: 10)
cashbackLabel.contentEdgeInsets = UIEdgeInsets(top: 1.5, left: 5, bottom: 1.5, right: 5)
cashbackLabel.layer.cornerRadius = 5
cashbackLabel.layer.borderWidth = 0
cashbackLabel.sizeToFit()
flex.addItem(cashbackLabel).margin(2)
}
}
rootFlexContainer.flex.layout()
if retailerTags?.count ?? 0 == 0 {
tagsView.isHidden = true
} else {
tagsView.isHidden = false
}
}
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
fileprivate func layout() {
rootFlexContainer.frame.size.width = frame.width - 20
rootFlexContainer.flex.layout(mode: .adjustHeight)
if(rootFlexContainer.frame.height != 0) {
tagsHeight.constant = rootFlexContainer.frame.height
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Following is view hierarchy from stroryboard

A few observations -
1. Unnecessary layoutIfNeeded() call inside awakeFromNib()
override func awakeFromNib() {
super.awakeFromNib()
/*
self.layoutIfNeeded() // Not Necessary, Remove it.
*/
// No other changes to current implementation
}
2. Following should not be necessary, remove it.
/* Not necessary, Remove it.
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
fileprivate func layout() {
rootFlexContainer.frame.size.width = frame.width - 20
rootFlexContainer.flex.layout(mode: .adjustHeight)
if(rootFlexContainer.frame.height != 0) {
tagsHeight.constant = rootFlexContainer.frame.height
}
}
*/
3. In the method, where you populate all the details, make following changes
func setSetupStoreUI() {
// No changes to current implementation
/* Remove this, we will update later
rootFlexContainer.flex.layout()
*/
if retailerTags?.count ?? 0 == 0 {
tagsView.isHidden = true
} else {
tagsView.isHidden = false
}
// Copied as is from `layout()`
rootFlexContainer.frame.size.width = frame.width - 20
rootFlexContainer.flex.layout(mode: .adjustHeight)
if (rootFlexContainer.frame.height != 0) {
tagsHeight.constant = rootFlexContainer.frame.height
}
// do a manual layout (on contentView, NOT self)
self.contentView.layoutIfNeeded()
}

You have to tell the table view controller that your cell height has changed.
Most common methods are protocol/delegate pattern or (swift preferred) closures.
For example...
In your cell class:
class MyTableViewCell: UITableViewCell {
// "callback" closure
var cellHeightChanged: (()->())?
// whatever happens that you need to change the cell height
func heightChanged() -> Void {
tagsHeight.constant = rootFlexContainer.frame.height
cellHeightChanged?()
}
}
Then, in your controller, in cellForRowAt:
cell.cellHeightChanged = {
tableView.performBatchUpdates(nil, completion: nil)
}

Related

My UITapGestureRecognizer affects all elements in TableViewCell

I am trying to do my first ever App, and i'm need to add UITapGestureRecognizer that will scale photo in TableViewCell.
And it is works, but not correctly — my Gesture scale not just photo in ViewCell but all elements in ViewCell. How could I fix this?
All my code for TableViewCell:
import UIKit
class PhotosCollectionViewCell: UICollectionViewCell {
static let identifier = "PhotosCollectionViewCell"
#IBOutlet weak var mainPhoto: UIImageView!
#IBOutlet weak var mainLabel: UILabel!
var isInScale: Bool = false
func configure(photo: PhotosInProfile) {
mainPhoto.image = UIImage(named: photo.mainPhoto)
mainLabel.text = "Date: \(photo.date)"
}
override func awakeFromNib() {
super.awakeFromNib()
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(imageDoubleTapped))
doubleTap.numberOfTapsRequired = 2
mainPhoto.isUserInteractionEnabled = true
mainPhoto.addGestureRecognizer(doubleTap)
}
#objc func imageDoubleTapped() {
if isInScale {
self.transform = .identity
} else {
self.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}
isInScale.toggle()
}
}
import UIKit
class PhotosCollectionViewCell: UICollectionViewCell {
static let identifier = "PhotosCollectionViewCell"
#IBOutlet weak var mainPhoto: UIImageView!
#IBOutlet weak var mainLabel: UILabel!
var isInScale: Bool = false
func configure(photo: PhotosInProfile) {
mainPhoto.image = UIImage(named: photo.mainPhoto)
mainLabel.text = "Date: \(photo.date)"
}
override func awakeFromNib() {
super.awakeFromNib()
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(imageDoubleTapped))
doubleTap.numberOfTapsRequired = 2
mainPhoto.isUserInteractionEnabled = true
mainPhoto.addGestureRecognizer(doubleTap)
}
#objc func imageDoubleTapped() {
if isInScale {
mainPhoto.transform = .identity
} else {
mainPhoto.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}
isInScale.toggle()
}
}

CollectionViewCell will not display dynamic images

I am creating a flip animation on the screen. On view load the page shows the back of the card fine. all 16 images are showing the back of the card. After clicking the button to flip, I need the CollectionViewCell to show different images (card_1.jpg, card_2.jpg, etc..) but only the first cell displays the image.
class CardsCollectionViewCell: UICollectionViewCell {
var deck: [Int] = []
#IBOutlet weak var numberLabel: UILabel!
let cardBackTag: Int = 0
let cardFrontTag: Int = 1
var cardViews: (frontView: UIImageView, backView: UIImageView)?
var imgViewFront: UIImageView!
var imgViewBack: UIImageView!
override func awakeFromNib() {
self.imgViewFront = self.createCardViewWithImage(imageName: "card_1", tag: self.cardFrontTag)
self.imgViewBack = self.createCardViewWithImage(imageName: "back-card", tag: self.cardBackTag)
self.cardViews = (frontView: self.imgViewFront, backView: self.imgViewBack)
self.contentView.addSubview(self.imgViewFront)
}
private func createCardViewWithImage(imageName: String, tag: Int) -> UIImageView {
let newCardImageView = UIImageView(frame: self.frame)
newCardImageView.image = UIImage(named: imageName)
newCardImageView.tag = tag
newCardImageView.clipsToBounds = true
newCardImageView.contentMode = .scaleAspectFill
return newCardImageView
}
func flipCardAnimation(indexPath: Int) {
if (self.imgViewBack.superview != nil) {
// front card
self.numberLabel.textColor = UIColor.white
self.numberLabel.backgroundColor = UIColor.orange
self.numberLabel.clipsToBounds = true
self.numberLabel.text = "\(self.deck[indexPath])"
self.numberLabel.isHidden = false
self.cardViews!.frontView.removeFromSuperview()
self.imgViewFront = self.createCardViewWithImage(imageName: "card_\(self.deck[indexPath])", tag: self.cardFrontTag)
self.cardViews = (frontView: self.imgViewFront, backView: self.imgViewBack)
} else {
// back card
self.deck = [Int](repeating: 0, count: 16)
self.numberLabel.isHidden = true
self.cardViews = (frontView: self.imgViewBack, backView: self.imgViewFront)
}
let transitionOptions = UIView.AnimationOptions.transitionFlipFromLeft
UIView.transition(with: self.contentView, duration: 0.5, options: transitionOptions, animations: {
self.cardViews!.backView.removeFromSuperview()
self.contentView.addSubview(self.cardViews!.frontView)
}, completion: {finished in
})
}
}
I followed this articles example to create the animation. https://medium.com/#lawrey/creating-a-flip-card-animation-with-uicollectionviewcell-swift-3-0-98bc96317fee
In my code above I have a label which displays the number at the indexPath inside the deck array. but not the image can someone tell me how to display all image dynamically? or what am I doing wrong?
So after spending a whole day yesterday I figured it's time to change my approach. I decided to create two images in the storyboard instead. Here is my final working code. This load all 16 cards with the back of the card photo and when a button is clicked the flip animation flips to random 16 card.
import UIKit
import Foundation
import ProgressHUD
class CardsCollectionViewCell: UICollectionViewCell {
var deck: [Int] = []
#IBOutlet weak var numberLabel: UILabel!
#IBOutlet weak var imgViewBack: UIImageView!
#IBOutlet weak var imgViewFront: UIImageView!
var cardBack: Bool = true
func flipCardAnimation(indexPath: Int) {
numberLabel.isHidden = true
let transitionOptions = UIView.AnimationOptions.transitionFlipFromLeft
UIView.transition(with: self.contentView, duration: 0.5, options: transitionOptions, animations: {
if self.cardBack == true {
self.deck = [Int](repeating: 0, count: NUMBER_OF_CARDS_IN_DECK)
self.imgViewBack.isHidden = false
self.imgViewFront.isHidden = true
} else {
self.numberLabel.isHidden = false
self.imgViewBack.isHidden = true
self.imgViewFront.isHidden = false
}
if (self.cardBack != true) {
// front card
self.numberLabel.text = "\(self.deck[indexPath])"
self.numberLabel.textColor = UIColor.white
self.numberLabel.backgroundColor = .red
self.numberLabel.layer.cornerRadius =
self.numberLabel.layer.frame.width/2
self.numberLabel.layer.masksToBounds = true
self.imgViewFront.image = UIImage(named: "card_\(self.deck[indexPath])")
self.imgViewFront.tag = self.deck[indexPath]
self.imgViewFront.contentMode = .scaleAspectFill
self.imgViewFront.clipsToBounds = true
self.imgViewFront.layer.cornerRadius = 12
} else {
// back card
print(self.deck)
self.numberLabel.text?.removeAll()
self.imgViewBack.image = UIImage(named: "back-card-1")
self.imgViewBack.tag = 1
self.imgViewBack.contentMode = .scaleAspectFill
self.imgViewBack.clipsToBounds = true
}
}, completion: {finished in
if self.cardBack == true {
self.cardBack = false
} else {
self.cardBack = true
}
})
}
}

How do I draw lines over an image within a ScrollView - Swift 3

I'm creating an app that allows the user to draw 2 rectangles over an image, contained within a scroll view. However, at the moment, the line does not appear to be drawn.
Here is the UIViewController that handles the drawing:
import UIKit
import CoreGraphics
import CoreData
class PhotoZoomController: UIViewController {
//Photo View's Variables
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
var photo: Photo!
var indicatorPoints: [CGPoint]!
var objectPoints: [CGPoint]!
var context: NSManagedObjectContext!
var brushWidth: CGFloat = 10.0;
var brushColor: CGColor = UIColor.cyan.cgColor
override func viewDidLoad() {
super.viewDidLoad()
photoImageView.image = photo.image
photoImageView.sizeToFit()
scrollView.contentSize = photoImageView.bounds.size
updateZoomScale()
updateConstraintsForSize(view.bounds.size)
view.backgroundColor = .black
}
var minZoomScale: CGFloat {
let viewSize = view.bounds.size
let widthScale = viewSize.width/photoImageView.bounds.width
let heightScale = viewSize.height/photoImageView.bounds.height
return min(widthScale, heightScale)
}
func updateZoomScale() {
scrollView.minimumZoomScale = minZoomScale
scrollView.zoomScale = minZoomScale
}
func updateConstraintsForSize(_ size: CGSize) {
let verticalSpace = size.height - photoImageView.frame.height
let yOffset = max(0, verticalSpace/2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
let xOffset = max(0, (size.width - photoImageView.frame.width)/2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
}
#IBAction func tappedInside(_ sender: Any) {
guard let sender = sender as? UITapGestureRecognizer else {
return
}
let touch = sender.location(in: self.photoImageView)
for i in 0...3 {
if indicatorPoints[i] == CGPoint() {
indicatorPoints[i] = touch
return
}
}
for i in 0...3 {
if objectPoints[i] == CGPoint() {
objectPoints[i] = touch
return
}
}
//This part isn't finished, but it's supposed to modify previous points
}
}
extension PhotoZoomController {
I feel like this is where my problems start. I know this code runs, because I've put a print statement in here and it ran.
func drawLine(between points: [CGPoint]) {
UIGraphicsBeginImageContextWithOptions(self.photoImageView.bounds.size, false, 0)
photoImageView.image?.draw(in: self.photoImageView.bounds)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.setLineCap(.round)
context.setLineWidth(brushWidth)
context.setStrokeColor(brushColor)
context.addLines(between: points)
context.strokePath()
UIGraphicsEndImageContext()
}
}
extension PhotoZoomController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return photoImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
if scrollView.zoomScale < minZoomScale {
dismiss(animated: true, completion: nil)
}
}
}
This is what the UIViewController currently looks like (maybe there's something wrong with the order of views?):
Storyboard picture of the ZoomController (This UIViewController)
You are saying
UIGraphicsBeginImageContextWithOptions
and
UIGraphicsEndImageContext
and in between them, while the context exists, you draw into it.
So far, so good.
But nowhere do you say
UIGraphicsGetImageFromCurrentImageContext
Therefore, the context, containing the result of your drawing, is just thrown away.

Swift - not detect the event of moving the Slider in Custom Cell

I am developing an application in swift 3 with the following interface:
I have to add some details about the legend. The legend consists of two views (firstView and secondView). Where a default "layout" is 0, until we click on it and that is when the detail of the cell is opened. Bells, a legend like this appears:
Currently the slider send events are as follows:
The interface consists of two views. The map that is the view of the bottom ("MainMapVC") that if we make a "swipe" to the right appears the legend of the map "LefSideViewController" formed by custom cells ("customCell").
I enclose the code of the three classes:
The "customCell":
import UIKit
protocol customCellDelegate {
func didTappedSwicht(cell: customCell)
func didMoveSlider(cell: customCell)
}
class customCell: UITableViewCell {
//MARK: OUTLETS VIEW 1
#IBOutlet weak var firstView: UIView!
#IBOutlet weak var firstViewLabel: UILabel!
#IBOutlet weak var swichtActiveLayer: UISwitch!
//MARK: OUTLETS VIEW 2
#IBOutlet weak var secondView: UIView!
#IBOutlet weak var secondViewLabel: UILabel!
#IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var idDeliveryResponse: UILabel!
#IBOutlet weak var minRangeDeliveryResponse: UILabel!
#IBOutlet weak var maxRangeDeliveryResponse: UILabel!
#IBOutlet weak var initialMinDeliveryResponse: UILabel!
#IBOutlet weak var initialMaxDeliveryResponse: UILabel!
#IBOutlet weak var sliderOpacity: UISlider!
// MARK: VARIABLES
var delegate: customCellDelegate!
override func awakeFromNib() {
super.awakeFromNib()
}
func setupWithModel(model: deliveriesLeftTableModel){
firstViewLabel.text = model.firstViewLabel
secondViewLabel.text = model.secondViewLabel
idDeliveryResponse.text = model.idDeliveryResponse
minRangeDeliveryResponse.text = model.minRangeDeliveryResponse
maxRangeDeliveryResponse.text = model.maxRangeDeliveryResponse
initialMinDeliveryResponse.text = model.initialMinDeliveryResponse
initialMaxDeliveryResponse.text = model.initialMaxDeliveryResponse
swichtActiveLayer.setOn(model.swichtActiveLayer, animated: true)
sliderOpacity.value = model.sliderOpacity
}
#IBAction func swichtValueChanged(_ sender: Any) {
delegate.didTappedSwicht(cell: self)
}
#IBAction func primaryActionTrigger(_ sender: Any){
print("primaryActionTrigger")
}
#IBAction func touchUpInside(_ sender: Any){
print("touchUpInside")
}
/*#IBAction func sliderValueChanged(_ sender: Any) {
delegate.didMoveSlider(cell: self)
}*/
var showsDetails = false {
didSet {
secondHeightConstraint.priority = showsDetails ? 250 : 900
}
}
}
 
The "LefSideViewController" is:
import UIKit
protocol customCellDelegate {
func didTappedSwicht(cell: customCell)
func didMoveSlider(cell: customCell)
}
class customCell: UITableViewCell {
//MARK: OUTLETS VIEW 1
#IBOutlet weak var firstView: UIView!
#IBOutlet weak var firstViewLabel: UILabel!
#IBOutlet weak var swichtActiveLayer: UISwitch!
//MARK: OUTLETS VIEW 2
#IBOutlet weak var secondView: UIView!
#IBOutlet weak var secondViewLabel: UILabel!
#IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var idDeliveryResponse: UILabel!
#IBOutlet weak var minRangeDeliveryResponse: UILabel!
#IBOutlet weak var maxRangeDeliveryResponse: UILabel!
#IBOutlet weak var initialMinDeliveryResponse: UILabel!
#IBOutlet weak var initialMaxDeliveryResponse: UILabel!
#IBOutlet weak var sliderOpacity: UISlider!
// MARK: VARIABLES
var delegate: customCellDelegate!
override func awakeFromNib() {
super.awakeFromNib()
}
func setupWithModel(model: deliveriesLeftTableModel){
firstViewLabel.text = model.firstViewLabel
secondViewLabel.text = model.secondViewLabel
idDeliveryResponse.text = model.idDeliveryResponse
minRangeDeliveryResponse.text = model.minRangeDeliveryResponse
maxRangeDeliveryResponse.text = model.maxRangeDeliveryResponse
initialMinDeliveryResponse.text = model.initialMinDeliveryResponse
initialMaxDeliveryResponse.text = model.initialMaxDeliveryResponse
swichtActiveLayer.setOn(model.swichtActiveLayer, animated: true)
sliderOpacity.value = model.sliderOpacity
}
#IBAction func swichtValueChanged(_ sender: Any) {
delegate.didTappedSwicht(cell: self)
}
#IBAction func sliderValueChanged(_ sender: Any) {
delegate.didMoveSlider(cell: self)
}
var showsDetails = false {
didSet {
secondHeightConstraint.priority = showsDetails ? 250 : 900
}
}
}
And the last one "MainMapVC":
import UIKit
import GoogleMaps
import MapKit
import ObjectMapper
//MARK: GLOBAL VARIABLES
let showLegend = UserDefaults.standard
let showLegendInformation = "showLegend"
var fields:WFSModel = WFSModel()
var allFields:[Field] = [Field]()
var total_parcels:[Parcel] = [Parcel]()
var poligons: [GMSPolygon] = []
var holes: [GMSMutablePath] = []
var snapShotsLegend : SnapshotsLegendModel = SnapshotsLegendModel()
var allDeliveries: [GMSURLTileLayer] = [GMSURLTileLayer]()
class MainMapVC: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate, GMSMapViewDelegate {
//OUTLETS:
#IBOutlet weak var dragLegend: NSLayoutConstraint!
#IBOutlet weak var iconDragLegend: UIImageView!
#IBOutlet weak var mapView: GMSMapView!
#IBOutlet weak var timer: UIActivityIndicatorView!
#IBOutlet weak var dragLengendView: UIView!
#IBOutlet weak var iconBarLegend: UIBarButtonItem!
//MARK: VARIABLES
let layer: WMSTileOverlay
var window: UIWindow?
var centerContainer: MMDrawerController?
var url = ""
let locationManager = CLLocationManager()
var coordenatesCellSelected: [Double] = [Double]()
var hole = GMSMutablePath()
var wfs:WFSModel = WFSModel()
var rect = GMSMutablePath()
let start = NSDate();
var polygonSelect = GMSPath()
var posSelecteTable:Int = 0
var menu_vc: LeftSideViewController!
//MARK:VIEWS
override func viewWillAppear(_ animated: Bool) {
super.viewDidLoad()
if coordenatesCellSelected.count != 0 {
let bounds = GMSCoordinateBounds(path: poligons[posSelecteTable].path!)
self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
poligons[posSelecteTable].fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.9)
poligons[posSelecteTable].strokeColor = .blue
poligons[posSelecteTable].strokeWidth = 2
poligons[posSelecteTable].map = mapView
}
if showLegend.bool(forKey: showLegendInformation) == true {
//self.dragLengendView.isHidden = false
self.iconBarLegend.isEnabled = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
menu_vc = self.storyboard?.instantiateViewController(withIdentifier: "LeftSideViewController") as! LeftSideViewController
menu_vc.delegate = self
self.timer.startAnimating()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
url = ""
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeRight)
self.view.addGestureRecognizer(swipeLeft)
if showLegend.bool(forKey: showLegendInformation) == false {
self.iconBarLegend.tintColor = UIColor.clear
self.iconBarLegend.isEnabled = false
}
if !allFields.isEmpty{
drawFields()
}
if allFields.isEmpty{
self.getCardfromGeoserver()
}
self.mapView.mapType = .satellite
}
#IBAction func menu_action(_ sender: UIBarButtonItem) {
if AppDelegate.menu_bool{
show_menu_left()
}else{
close_menu_left()
}
}
func show_menu_left(){
UIView.animate(withDuration: 0.6) { ()->Void in
self.menu_vc.view.frame = CGRect(x: 0, y: 60, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
self.menu_vc.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
self.addChildViewController(self.menu_vc)
self.view.addSubview(self.menu_vc.view)
AppDelegate.menu_bool = false
}
}
func close_menu_left(){
UIView.animate(withDuration: 0.6, animations: { ()->Void in
self.menu_vc.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 60, width: -UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
}) { (finished) in
self.menu_vc.view.removeFromSuperview()
}
AppDelegate.menu_bool = true
}
func respondToGesture(gesture: UISwipeGestureRecognizer){
switch gesture.direction{
case UISwipeGestureRecognizerDirection.right:
show_menu_left()
case UISwipeGestureRecognizerDirection.left:
close_on_swipe()
default:
break
}
}
func close_on_swipe(){
if AppDelegate.menu_bool{
show_menu_left()
}else{
close_menu_left()
}
}
//MARK: FUNCITIONS
required init?(coder aDecoder: NSCoder) {
self.layer = WMSTileOverlay(urlArg: url)
super.init(coder: aDecoder)
}
func getCardfromGeoserver() {
mapView.clear()
//mapView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 40.4256572451179, longitude: -3.18201821297407), zoom: 5.5, bearing: 0, viewingAngle: 0)
//MAP POSITION WITH DIFERENTS LAYERS
mapView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 39.59955969890008, longitude: -0.6421281303940684), zoom: 18.0, bearing: 0, viewingAngle: 0)
let WFS_JSON = "http://192.168.0.160:8080/geoserver/LordWor/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=LordWor:hemav-fincas&maxFeatures=1721&outputFormat=json"
if allFields.isEmpty {
let mapsFacade = MapsFacade()
mapsFacade.coordinatesWFS(url: WFS_JSON,
callbackFuncionOK: coordinatesWFSOK,
callbackFunctionERROR: coordinatesWFSOKERROR)
}
}
func coordinatesWFSOK( WFS_Response: WFSModel) {
let fields = WFS_Response.copyFieldswfs()
wfs = WFS_Response
for feature in 1...(wfs.features.count) {
//MARK: INSERT DATA FIELDS
DataBaseManagement.shared.addFields(inputPropertyIDFarming : wfs.features[feature - 1].properties.propertyIDFarming,
inputPropertyProducer : wfs.features[feature - 1].properties.propertyProducer,
inputPropertyVariety : wfs.features[feature - 1].properties.propertyVariety,
inputPropertyLand : wfs.features[feature - 1].properties.propertyLand)
for parcel in 1...(wfs.features[feature - 1].geometry.coordinates.count) {
if wfs.features[feature - 1].geometry.coordinates[parcel - 1].count == 1{//MARK: Without Hole
for poligon in 1...(wfs.features[feature - 1 ].geometry.coordinates[parcel - 1].count) {
//MARK: INSERT DATA FIELDS
DataBaseManagement.shared.addParcels(inputId_field: feature, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][0]))
}
}else{
for id in 1...(wfs.features[feature - 1].geometry.coordinates[parcel - 1].count) {//MARK: With Hole
if id == 1{
//MARK: INSERT COOERDENATES PARCEL
DataBaseManagement.shared.addParcels(inputId_field: feature, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][0]))
}else{
//MARK: this row contains all points for create a hole
//DataBaseManagement.shared.addHoles(inputId_hole: parcel, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][id - 1]))
//print("-------FIN PARCELA HOLE \(id - 1)---------")
}
}
}
}
}
//MARK: Get all group of Parcels
if allFields.count == 0 {
allFields = DataBaseManagement.shared.showAllFields()
total_parcels = DataBaseManagement.shared.showAllParcels()
}
drawFields()
}
func deleteAllParcels(){
for i in 0...total_parcels.count - 1 {
DataBaseManagement.shared.deleteAllParcels(inputId: i)
}
}
func deleteAllFields(){
for i in 0...allFields.count - 1 {
DataBaseManagement.shared.deleteAllFields(inputId: i)
}
}
func drawFields(){
//MARK: Field All Array wiht all (properrties for field and yours parcels)
for i in 0...allFields.count - 1{
let arr = try! JSONSerialization.jsonObject(with: total_parcels[i]._json_Parcel.data(using: .utf8)!, options: []) as! [[Double]]
allFields[i]._parcel.append(total_parcels[i]._json_Parcel);
//MARK: SAVE LATITUDE AND LONGITUDE IN ARRAY
for j in 0...arr.count - 1{
let longitude = arr[j][0]//latitud
let latitude = arr[j][1]//longitud
rect.add(CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
}
//MARK: DRAW ON THE MAP
let polygon = GMSPolygon()
polygon.path = rect
poligons.append(polygon)
rect = GMSMutablePath()
polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.3)
polygon.strokeColor = .blue
polygon.strokeWidth = 2
polygon.map = mapView
}
let end = NSDate()
self.timer.stopAnimating()
print("TIME CHARGE 'MAIN MAP'")
print(start)
print(end)
}
let urlSnapshot = "..."
func getDeliverablesForField(){
let deliverablesFacade = DeliverablesFacade()
deliverablesFacade.snapshots(url: urlSnapshot,
callbackFuncionOK: snapshotsOK,
callbackFunctionERROR: snapshotsERROR)
}
func snapshotsOK( snapshotsResponse: SnapshotsLegendModel) {
snapShotsLegend = snapshotsResponse.copySnapshots()
print("end recover fields")
}
func snapshotsERROR(_ httpCode: Int,nsError: NSError) {
if httpCode == -1 {
print(nsError)
print(httpCode)
}else{
print(nsError)
print(httpCode)
}
}
var onlyOnetime = 0
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
for polygon in poligons{
if (GMSGeometryContainsLocation(CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude), polygon.path!, true)) {
onlyOnetime = onlyOnetime + 1
if onlyOnetime == 1{
getDeliverablesForField()
showLegend.setValue(true, forKey: showLegendInformation)
let bounds = GMSCoordinateBounds(path: polygon.path!)
self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
self.iconBarLegend.isEnabled = true
self.iconBarLegend.tintColor = UIColor.black
}
polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.9)
polygon.strokeColor = .blue
polygon.strokeWidth = 2
polygon.map = mapView
//self.viewDidLoad()
}
else{
polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.3)
polygon.strokeColor = .blue
polygon.strokeWidth = 2
polygon.map = mapView
}
}
}
func coordinatesWFSOKERROR(_ httpCode: Int,nsError: NSError) {
if httpCode == -1 {
print(nsError)
print(httpCode)
}else{
print(nsError)
print(httpCode)
}
}
#IBAction func goToAdvancedSearch(_ sender: Any) {
let advancedSearch: AdvancedSearchVC = UIStoryboard(name: "AdvancedSearch", bundle: nil).instantiateViewController(withIdentifier: "AdvancedSearchVC") as! AdvancedSearchVC
self.navigationController?.pushViewController(advancedSearch, animated: false)
}
}
extension MainMapVC: LeftSideDelegate {
func sendShapeDelivery(deliveryPos : Int){
if feedModelDeliveries[deliveryPos].swichtActiveLayer == true {
if true {
print("Not exist deliverable -> call WMS")
let nameDelivery = snapShotsLegend.legendEntries[0].deliverables[deliveryPos].url_layer
let urls: GMSTileURLConstructor = { (x: UInt, y: UInt, zoom: UInt) -> URL in
let bbox = self.layer.bboxFromXYZ(x, y: y, z: zoom)
let urlKN = "http://192.168.0.160:8080/geoserver/LordWor/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&tiled=true&STYLES=line&layers=LordWor:\(nameDelivery)&styles=&WIDTH=256&HEIGHT=256&SRS=EPSG:3857&BBOX=\(bbox.left),\(bbox.bottom),\(bbox.right),\(bbox.top)"
print("PETICION WMS DEL LALER: \(nameDelivery)")
return URL(string: urlKN)!
}
let tileLayer: GMSURLTileLayer = GMSURLTileLayer(urlConstructor: urls)
allDeliveries.append(tileLayer)
tileLayer.opacity = 0.5
tileLayer.map = self.mapView
}else{
let tileLayer: GMSURLTileLayer = allDeliveries[deliveryPos]
tileLayer.opacity = 0.5
tileLayer.map = self.mapView
}
}else{
let tileLayer: GMSURLTileLayer = allDeliveries[deliveryPos]
tileLayer.opacity = 0
tileLayer.map = self.mapView
}
}
}
The application communicates with protocols and delegates. For example, when we click on the swicht of the legend, the class "customCell" is able to detect the event "swichtValueChanged" and send it to a "didTappedSwicht" delegate of "LeftSideViewController", but when we move the slider the "customCell" class is not Able to detect the event "sliderValueChanged" and takes the event to close the view (because the legend on the left is closed with a swipe on the left).
How can I make it to detect the event of the slider and not to close the view?
Thank you
You should bind your Slider with two Events "Primary Action Triggered" and "Touch Up Inside"
Here I attached Image for your reference
and remove left swipe and right swipe gesture on this method
Method Description and code
1 "Primary Action Triggered"
When You click on slider the method will call "Primary Action Triggered"
Note : Disable your gesture
(UISwipeGestureRecognizerDirection.right and UISwipeGestureRecognizerDirection.left)
2 Touch Up Inside
Note : Enable your gesture both gesture
(UISwipeGestureRecognizerDirection.right and UISwipeGestureRecognizerDirection.left)

Swift Expected Declaration error? What is wrong with my code?

I have been learning how to code in Swift and followed some tutorials. While following a tutorial to make a zigzag-like game, I ran into an error that I don't know how to fix.
if (y > 720) {
low = true
}
The code above gives me an error Expected Declaration.
The following is the rest of my code
import UIKit
class ViewController: UIViewController {
#IBAction func Play(sender: AnyObject) {
TapsValid = true
BallChange = true
self.GameOver.hidden = true
self.Retry.hidden = true
self.Ball.hidden = false
self.Logo.hidden = true
self.Play.hidden = true
self.ScoreBoard.hidden = true
self.Ball.center.x = 178.0
self.Ball.center.y = 390.0
self.Pillar1.center = CGPointMake(175.0 , 436.0)
self.Pillar2.center = CGPointMake(214.0 , 407.0)
timer = NSTimer.scheduledTimerWithTimeInterval(0.045, target: self , selector: Selector("movement"), userInfo: nil, repeats: true)
self.Pillar3.center = pillarPlacement(Pillar2.center.x, y: Pillar2.center.y)
self.Pillar4.center = pillarPlacement(Pillar3.center.x, y: Pillar3.center.y)
self.Pillar5.center = pillarPlacement(Pillar4.center.x, y: Pillar4.center.y)
self.Pillar6.center = pillarPlacement(Pillar5.center.x, y: Pillar5.center.y)
self.Pillar7.center = pillarPlacement(Pillar6.center.x, y: Pillar6.center.y)
self.Pillar8.center = pillarPlacement(Pillar7.center.x, y: Pillar7.center.y)
self.Pillar9.center = pillarPlacement(Pillar8.center.x, y: Pillar8.center.y)
self.Pillar10.center = pillarPlacement(Pillar9.center.x, y: Pillar9.center.y)
self.Pillar1.hidden = false
self.Pillar2.hidden = false
self.Pillar3.hidden = false
self.Pillar4.hidden = false
self.Pillar5.hidden = false
self.Pillar6.hidden = false
self.Pillar7.hidden = false
self.Pillar8.hidden = false
self.Pillar9.hidden = false
self.Pillar10.hidden = false
self.PillarTop.hidden = false
self.PillarTop2.hidden = false
self.PillarTop3.hidden = false
}
#IBAction func Retry(sender: AnyObject) {
}
#IBOutlet weak var Pillar10: UIImageView!
#IBOutlet weak var Pillar9: UIImageView!
#IBOutlet weak var Pillar8: UIImageView!
#IBOutlet weak var Pillar7: UIImageView!
#IBOutlet weak var Pillar6: UIImageView!
#IBOutlet weak var Pillar5: UIImageView!
#IBOutlet weak var Pillar4: UIImageView!
#IBOutlet weak var Pillar3: UIImageView!
#IBOutlet weak var Pillar2: UIImageView!
#IBOutlet weak var Pillar1: UIImageView!
#IBOutlet weak var PillarTop3: UIImageView!
#IBOutlet weak var PillarTop2: UIImageView!
#IBOutlet weak var PillarTop: UIImageView!
#IBOutlet weak var Play: UIButton!
#IBOutlet weak var ScoreBoard: UIImageView!
#IBOutlet weak var Retry: UIButton!
#IBOutlet weak var Logo: UIImageView!
#IBOutlet weak var GameOver: UIImageView!
#IBOutlet weak var Ball: UIImageView!
var timer = NSTimer()
var TapsValid:Bool?
var BallRight:Bool?
var BallChange:Bool?
override func viewDidLoad() {
super.viewDidLoad()
self.GameOver.hidden = true
self.Retry.hidden = true
self.Ball.hidden = true
self.Logo.hidden = false
self.Play.hidden = false
self.ScoreBoard.hidden = true
self.Pillar1.hidden = true
self.Pillar2.hidden = true
self.Pillar3.hidden = true
self.Pillar4.hidden = true
self.Pillar5.hidden = true
self.Pillar6.hidden = true
self.Pillar7.hidden = true
self.Pillar8.hidden = true
self.Pillar9.hidden = true
self.Pillar10.hidden = true
self.PillarTop.hidden = true
self.PillarTop2.hidden = true
self.PillarTop3.hidden = true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if TapsValid == true {
if BallRight == true {
BallChange = false
} else {
BallChange = true
}
}
}
func movement() {
if BallChange == false{
BallRight = false
} else {
BallRight = true
}
if BallRight == true {
Ball.center.x += 6.5
Ball.center.y -= 0.5
} else {
Ball.center.x -= 6.5
Ball.center.y -= 0.5
}
Ball.center.y += 0.5
Pillar1.center.y += 5
Pillar2.center.y += 5
Pillar3.center.y += 5
Pillar4.center.y += 5
Pillar5.center.y += 5
Pillar6.center.y += 5
Pillar7.center.y += 5
Pillar8.center.y += 5
Pillar9.center.y += 5
Pillar10.center.y += 5
}
func movePillarUp(floatx: CGFloat, floaty: CGFloat, pillarNumber: Int) -> (CGPoint) {
var center = CGPointMake(floatx, floaty)
if checkPillarPosition(floaty) == true {
switch pillarNumber{
case 1:
center = pillarPlacement(self.Pillar10.center.x, y: self.Pillar10.center.y)
break
case 2:
center = pillarPlacement(self.Pillar1.center.x, y: self.Pillar2.center.y)
break
case 3:
center = pillarPlacement(self.Pillar2.center.x, y: self.Pillar2.center.y)
break
case 4:
center = pillarPlacement(self.Pillar3.center.x, y: self.Pillar3.center.y)
break
case 5:
center = pillarPlacement(self.Pillar4.center.x, y: self.Pillar4.center.y)
break
case 6:
center = pillarPlacement(self.Pillar5.center.x, y: self.Pillar5.center.y)
break
case 7:
center = pillarPlacement(self.Pillar6.center.x, y: self.Pillar6.center.y)
break
case 8:
center = pillarPlacement(self.Pillar7.center.x, y: self.Pillar7.center.y)
break
case 9:
center = pillarPlacement(self.Pillar8.center.x, y: self.Pillar8.center.y)
break
case 10:
center = pillarPlacement(self.Pillar9.center.x, y: self.Pillar9.center.y)
break
default:
break
}
}
return(center)
}
func checkPillarPosition(y: CGFloat) -> Bool {
var low = false}
if (y > 720) {
low = true
}
//This function moves pillars arround randomally
func pillarPlacement(x: CGFloat,y: CGFloat) -> (CGPoint) {
var PillarNewX: CGFloat
var PillarNewY: CGFloat
let random: Int = Int(arc4random() % 2)
if random == 1 {
PillarNewX = x + 39
PillarNewY = y - 29
if PillarNewX >= 319 {
PillarNewX = x - 40
PillarNewY = y - 30
}
} else {
PillarNewX = x - 40
PillarNewY = y - 30
if PillarNewX <= 17 {
PillarNewX = x + 39
PillarNewY = y - 29
}
}
let NewPillarCenter = CGPointMake(PillarNewX, PillarNewY)
return(NewPillarCenter)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The if statement is not in a function, I think you may want to add it to the checkPillarPosition. The updated code would look like this:
func checkPillarPosition(y: CGFloat) -> Bool {
var low = false
if (y > 720) {
low = true
return true
} else {
return false
}
}
This would remove your error and would fix your problem. Hope it helps!

Resources