Swipe slide and move imageView position - ios

in my code some time it increases a lot and some time let the image position increase and decrease.
IBOutlet weak var bgImage: UIImageView!
IBOutlet weak var sliders: UISlider!
IBOutlet weak var imgViews: UIImageView!
var location = CGPoint(x: 0, y: 0)
var valueOFButterFly = 54.5
var lastValueOfSlider = Float()
#IBAction func sliderValue(_ sender: UISlider) {
print(sender.value)
if lastValueOfSlider >= sender.value {
valueOFButterFly = valueOFButterFly - 1
print("new value \(valueOFButterFly)")
imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)
}
else if (lastValueOfSlider < sender.value) {
valueOFButterFly = valueOFButterFly + 1
print("new value \(valueOFButterFly)")
imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)
}
else {
print("else if")
}
self.lastValueOfSlider = sender.value
}

In case you want to match the imageView's centre with that of the slider value, you need to set the slider's currentValue as imageView's centre instead of incrementing or decrementing by 1.
Also, update the imageView.center in valueOFButterFly's didSet property observer instead of updating it multiple times throughout the code.
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var slider: UISlider!
var lastValueOfSlider = Float()
var valueOFButterFly = 54.5 {
didSet {
imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
}
}
override func viewDidLoad() {
super.viewDidLoad()
slider.minimumValue = 0
slider.maximumValue = Float(UIScreen.main.bounds.width)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
}
#IBAction func sliderValue(_ sender: UISlider) {
print(sender.value)
valueOFButterFly = Double(sender.value)
self.lastValueOfSlider = sender.value
}
}
In the above code, I've used
slider.minimumValue = 0
slider.maximumValue = Float(UIScreen.main.bounds.width)
You can configure the above properties as per your requirement.

Related

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)

Starting an action when View Controller Loads

How do I start an action when the view controller loads on screen?
I've managed to do the function I want with an #IBAction but I don't want a button press for the action to happen, I want it to start the action when the page loads
any thoughts?
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
#IBAction func Animate(sender: AnyObject) {
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
Use :-
Basic idea here is that whenever your view will load corresponding class will look up to viewWillAppear(animated: Bool) function and if it's present in the code it will execute all the code in it.The moment that particular view is about to appear on your UI, your code block in viewWillAppear(animated: Bool) will get called.
class ViewController: UIViewController {
var progress: KDCircularProgress!
#IBOutlet weak var Label1: UILabel!
var LabelText = String()
var scorestart = 1.0
var anglepercent = 3.6
override func viewDidLoad() {
super.viewDidLoad()
Label1.text = LabelText
view.backgroundColor = UIColor(white: 0.22, alpha: 1)
}
override func viewWillAppear(animated :Bool) {
super.viewWillAppear(animated)
progressActn()
//Setting up your progress layer
animateActn()
//Animating that progress layer
}
#IBAction func Animate(sender: AnyObject) {
animateActn()
}
func animateActn(){
progress.angle = Double(scorestart * anglepercent)
progress.animateFromAngle(0, toAngle: 270, duration: 2) {
completed in
if completed {
print("animation stopped, completed")
} else {
print("animation stopped, was interrupted")
}
}
}
func progressActn(){
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.3
progress.clockwise = true
progress.gradientRotateSpeed = 10
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.yellowColor())
progress.center = CGPoint(x: view.center.x, y: view.center.y + 25)
view.addSubview(progress)
}
}

How to create connected sliders in Swift?

I'm trying to create a control with 3 vertical sliders. I want the draggable dots on the sliders to have lines connecting them. Any advice on how to go about making this?
You can create UIBezierPath, use that path in a CAShapeLayer, and add that layer as a sublayer to your view's layer.
The only issue is figuring out the start and end points for your lines, and that can be done by looking at the sliders' thumbRectForBounds. And assuming you used a standard UISliderView and simply rotated it, you should make sure to convert the point to the parent's coordinate system:
class ViewController: UIViewController {
#IBOutlet weak var slider1: UISlider!
#IBOutlet weak var slider2: UISlider!
#IBOutlet weak var slider3: UISlider!
lazy var lineLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.lineWidth = 3
layer.fillColor = UIColor.clearColor().CGColor
layer.strokeColor = UIColor.redColor().CGColor
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
[slider1, slider2, slider3].forEach { slider in
slider.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
}
view.layer.insertSublayer(lineLayer, atIndex: 0)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
lineLayer.frame = view.bounds
updatePathBetweenSliders()
}
#IBAction func didChangeValue(sender: UISlider) {
updatePathBetweenSliders()
}
private func updatePathBetweenSliders() {
let path = UIBezierPath()
path.moveToPoint(slider1.thumbCenter())
path.addLineToPoint(slider2.thumbCenter())
path.addLineToPoint(slider3.thumbCenter())
lineLayer.path = path.CGPath
}
}
Where:
extension UISlider {
func thumbCenter() -> CGPoint {
let thumbRect = thumbRectForBounds(bounds, trackRect: trackRectForBounds(bounds), value: value)
let thumbCenter = CGPoint(x: thumbRect.midX, y: thumbRect.midY)
return convertPoint(thumbCenter, toView: superview)
}
}
That yields:
If you want to animate the sliders at any point (like I do at the end of that animated GIF), you'll probably have to resort to a CADisplayLink to update the values:
let animationDuration = 0.5
var originalValues: [Float]!
var targetValues: [Float]!
var startTime: CFAbsoluteTime!
#IBAction func didTapResetButton(sender: UIButton) {
let sliders = [slider1, slider2, slider3]
originalValues = sliders.map { $0.value }
targetValues = sliders.map { _ in Float(0.5) }
startTime = CFAbsoluteTimeGetCurrent()
let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
func handleDisplayLink(displayLink: CADisplayLink) {
let percent = Float((CFAbsoluteTimeGetCurrent() - startTime) / animationDuration)
let sliders = [slider1, slider2, slider3]
if percent < 1 {
for (index, slider) in sliders.enumerate() {
slider.value = (targetValues[index] - originalValues[index]) * percent + originalValues[index]
}
} else {
for (index, slider) in sliders.enumerate() {
slider.value = targetValues[index]
}
displayLink.invalidate()
}
updatePathBetweenSliders()
}

Swift UIView custom view won't update after ViewController action

I want the stepper in the View Controller to update the color in my custom UIView every time it is clicked. I'm not sure if the problem is due to the instance of the class or that the values of the variables (redd1, greenn1, and bluee1) are not being changed.
This is my first file:
class ViewController: UIViewController {
var colors = UIView1();
#IBOutlet var redStepper: UIStepper!
#IBOutlet var greenStepper: UIStepper!
#IBOutlet var blueStepper: UIStepper!
#IBAction func redChange(sender: UIStepper)
{
redValue.text = Int(sender.value).description;
colors.redd1 = Double(sender.value);
//self.view.setNeedsDisplay()
}
#IBAction func greenChange(sender: UIStepper)
{
greenValue.text = Int(sender.value).description;
colors.greenn1 = Double(sender.value);
//self.view.setNeedsDisplay()
}
#IBAction func blueChange(sender: UIStepper)
{
blueValue.text = Int(sender.value).description;
colors.bluee1 = Double(sender.value);
//self.view.setNeedsDisplay()
}
}
This is my second file:
class UIView1: UIView {
var redd1 = 0.0;
var greenn1 = 0.0;
var bluee1 = 0.0;
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect)
{
let circle = UIView(frame: CGRect(x: -75.0, y: -40.0, width: 200.0, height: 200.0))
circle.layer.cornerRadius = 50.0;
let startingColor = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat(greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
circle.backgroundColor = startingColor;
addSubview(circle);
}
}
drawRect is only called when the view is being added, so in your example, drawRect is called once, and not after changing the stepper.
Instead, change your stepper file to:
#IBOutlet var redStepper: UIStepper!
#IBOutlet var greenStepper: UIStepper!
#IBOutlet var blueStepper: UIStepper!
#IBAction func redChange(sender: UIStepper) {
redValue.text = Int(sender.value).description;
colors.redd1 = Double(sender.value);
updateColor()
}
#IBAction func greenChange(sender: UIStepper) {
greenValue.text = Int(sender.value).description;
colors.greenn1 = Double(sender.value);
updateColor()
}
#IBAction func blueChange(sender: UIStepper) {
blueValue.text = Int(sender.value).description;
colors.bluee1 = Double(sender.value);
updateColor()
}
And then add the updateColor function to your UIView1 class:
class UIView1: UIView {
var redd1 = 0.0;
var greenn1 = 0.0;
var bluee1 = 0.0;
func updateColor() {
let circle = UIView(frame: CGRect(x: -75.0, y: -40.0, width: 200.0, height: 200.0))
circle.layer.cornerRadius = 50.0;
let startingColor = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat(greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
circle.backgroundColor = startingColor;
addSubview(circle);
}
}

Resources