I am using Charts to create custom graphs in an application. The one thing I am having trouble with is detecting touch events on the chart marker that is presented for the current value. I want to perform and action based on the marker that was tapped. The action should take in the data entry represented by the tapped marker.
I have read through Selectable marker view & images at Y axis, but still haven't been able to produce a viable solution.
It would be great if someone could provide a code sample, or more detailed explanation than found in the link above, to point me in the right direction.
Thanks
As per your requirement Charts library already have that method in its delegate.
Please check below code :
Assign delegate to your ChartView like below
lineChartView.delegate = self
Implement Delegate method in your class
public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
}
Here you can write your code while user click on chart.
Hope this info will helps!
I ended up solving this by subclassing the ChartView of my choice and overriding the existing tap gesture recognizer with my own.
Example
final class CustomChartView: BarChartView {
...
private func initialize() {
...
let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
self.addGestureRecognizer(tap)
}
#objc func tapRecognized(_ recognizer: UITapGestureRecognizer) {
guard data !== nil else { return }
switch recognizer.state {
case .ended:
// Detect whether or not the touch was inside a marker that was being presented
// Otherwise, add/remove highlight as necessary
if let marker = self.marker as? BalloonMarker {
let location = recognizer.location(in: self)
if !highlighted.isEmpty && marker.rect.contains(location) {
// In my case, I created custom property 'vertex' on BalloonMarker for easy reference to get `xValue`
let xValue = self.getTransformer(forAxis: .left).valueForTouchPoint(marker.vertex).x
// Do what you need to here with tap (call function, create custom delegate and trigger it, etc)
// In my case, my chart has a marker tap delegate
// ex, something like: `markerTapDelegate?.tappedMarker()`
return
}
}
// Default tap handling
guard isHighLightPerTapEnabled else { return }
let h = getHighlightByTouchPoint(recognizer.location(in: self))
if h === nil || h == self.lastHighlighted {
lastHighlighted = nil
highlightValue(nil, callDelegate: true)
} else {
lastHighlighted = h
highlightValue(h, callDelegate: true)
}
default:
break
}
}
Related
I'm using BulletinBoard (BLTNBoard) to create dialogs in my iOS app. There's an option to embed image inside it. I would like to extend it's functionality and allow user to manipulate this image using tap gesture. But eventually when I assign a gesture to it's imageView using addGestureRecognizer nothing happens.
Here's how I initiliaze bulletin and add gesture to the image:
class ViewController: UIViewController {
lazy var bulletinManager: BLTNItemManager = {
let rootItem: BLTNPageItem = BLTNPageItem(title: "")
return BLTNItemManager(rootItem: rootItem)
}()
override func viewDidLoad() {
//etc code
let bulletinManager: BLTNItemManager = {
let item = BLTNPageItem(title: "Welcome")
item.descriptionText = "Pleas welcome to my app"
item.actionButtonTitle = "Go"
item.alternativeButtonTitle = "Try to tap here"
item.requiresCloseButton = false
item.isDismissable = false
item.actionHandler = { item in
self.bulletinManager.dismissBulletin()
}
item.alternativeHandler = { item in
//do nothing by now
}
//
item.image = UIImage(named: "welcome")
//adding gesture to its imageView
item.imageView?.isUserInteractionEnabled=true
let tap = UITapGestureRecognizer(target: self, action: Selector("tapTap:"))
item.imageView?.addGestureRecognizer(tap)
return BLTNItemManager(rootItem: item)
}()
}
#objc func tapTap(gestureRecognizer: UITapGestureRecognizer) {
print("TAPTAP!!!!!!")
}
}
and nothing happens at all (no message printed in console).
However if I assign action inside alternative button it works as expected:
item.alternativeHandler = { item in
item.imageView?.isUserInteractionEnabled=true
let tap = UITapGestureRecognizer(target: self, action: Selector("tapTap:"))
item.imageView?.addGestureRecognizer(tap)
}
I guess the only thing which can prevent me to assign the tap event to it properly is that imageView becomes available much later than the bulletin is created (for example only when it is shown on the screen).
Could you please help and correct my code. Thanks
upd.
Ok, based on Philipp's answer I have the following solution:
class myPageItem: BLTNPageItem {
override func makeContentViews(with interfaceBuilder: BLTNInterfaceBuilder) -> [UIView] {
let contentViews = super.makeContentViews(with: interfaceBuilder)
let imageView=super.imageView
imageView?.isUserInteractionEnabled=true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapTap))
imageView?.addGestureRecognizer(tap)
return contentViews
}
#objc func tapTap(gestureRecognizer: UITapGestureRecognizer) {
print("TAPTAP!!!!!!")
}
}
When you're working with an open source library, it's easy to check out the source code to find the answer.
As you can see here, image setter doesn't initiate the image view.
Both makeContentViews makeArrangedSubviews (which are responsible for views initializing) doesn't have any finish notification callbacks.
Usually in such cases I had to fork the repo and add functionality by myself - then I'll make a pull request if I think this functionality may be needed by someone else.
But luckily for you the BLTNPageItem is marked open, so you can just subclass it. Override makeContentViews and add your logic there, something like this:
class YourOwnPageItem: BLTNPageItem {
override func makeContentViews(with interfaceBuilder: BLTNInterfaceBuilder) -> [UIView] {
let contentViews = super.makeContentViews(with: interfaceBuilder)
// configure the imageView here
return contentViews
}
}
I have mapView with some annotations. I need to do separate action for both user dragged region change and set region(Automatically focus). Is there any way to find user dragged manually or not while regionDidChangeAnimated method calling.
I have checked all default properties for MKMapView, MKVisibleRect, region. There is no property related to finding for detect map view changed with user dragged manually or not
Unfortunately, you have to do this using a UIPanGestureRecognizer.
I have used, with success, A UIPanGestureRecognizer like the following:
lazy var mapPanGestureRecognizer: UIPanGestureRecognizer = {
let gr = UIPanGestureRecognizer(target: self, action: #selector(draggedMap))
gr.delegate = self
return gr
}()
You will also have to add the UIPanGestureRecognizer to the map with
yourMap.addGestureRecognizer(mapPanGestureRecognizer)
You can then manage what happens in the #selector function by checking the state of the gesture, like so
#objc func draggedMap(panGestureRecognizer: UIPanGestureRecognizer) {
// Check to see the state of the passed panGestureRocognizer
if panGestureRecognizer.state == UIGestureRecognizer.State.began {
// Do something
}
}
In the AR example project of apple there is an option for placing a chair in the room. What do I need to do to place multiple chairs in the code?
Would a simple append function do the trick?
When I tap on the chair option I need the first chair to be placed in the plane. If I tap again the option the chair should be placed once again. And I know I will need a delete function for this too. So how can I detect a long tap by the user?
A basic tap function to add a ball each time you tap the display.
#objc func handleTap(_ gesture: UITapGestureRecognizer) {
let results = self.sceneView.hitTest(gesture.location(in: gesture.view), types: ARHitTestResult.ResultType.featurePoint)
guard let result: ARHitTestResult = results.first else {
return
}
// create a simple ball
let sphereNode = SCNNode(geometry: SCNSphere(radius: 0.2)
// create position of ball based on tap result
let position = SCNVector3Make(result.worldTransform.columns.3.x, result.worldTransform.columns.3.y, result.worldTransform.columns.3.z)
// set position of ball before adding to scene
sphereNode?.position = position
// each tap adds a new instance of the ball.
self.sceneView.scene.rootNode.addChildNode(sphereNode!)
}
If you need the full swift code to get started...take a look at this earlier post adds a cube.scn from a remote url
You can do long press with
#objc func longPress(_ gesture: UILongPressGestureRecognizer) {
}
But its better to just detect you've tapped on an existing sphereNode you want to remove. You could add something like this to the above function.
let tappedNode = self.sceneView.hitTest(gesture.location(in: gesture.view), options: [:])
if !tappedNode.isEmpty {
let node = tappedNode[0].node
node.removeFromParent()
} else {
// add my new node
}
I am using a custom path animation on UIImageView items for a Swift 3 project. The code outline is as follows:
// parentView and other parameters are configured externally
let imageView = UIImageView(image: image)
imageView.isUserInteractionEnabled = true
let gr = UITapGestureRecognizer(target: self, action: #selector(onTap(gesture:)))
parentView.addGestureRecognizer(gr)
parentView.addSubview(imageView)
// Then I set up animation, including:
let animation = CAKeyframeAnimation(keyPath: "position")
// .... eventually ....
imageView.layer.add(animation, forKey: nil)
The onTap method is declared in a standard way:
func onTap(gesture:UITapGestureRecognizer) {
print("ImageView frame is \(self.imageView.layer.visibleRect)")
print("Gesture occurred at \(gesture.location(in: FloatingImageHandler.parentView))")
}
The problem is that each time I call addGestureRecognizer, the previous gesture recognizer gets overwritten, so any detected tap always points to the LAST added image, and the location is not detected accurately (so if someone tapped anywhere on the parentView, it would still trigger the onTap method).
How can I detect a tap accurately on per-imageView basis? I cannot use UIView.animate or other methods due to a custom path animation requirement, and I also cannot create an overlay transparent UIView to cover the parent view as I need these "floaters" to not swallow the events.
It is not very clear what are you trying to achieve, but i think you should add gesture recognizer to an imageView and not to a parentView.
So this:
parentView.addGestureRecognizer(gr)
Should be replaced by this:
imageView.addGestureRecognizer(gr)
And in your onTap function you probably should do something like this:
print("ImageView frame is \(gesture.view.layer.visibleRect)")
print("Gesture occurred at \(gesture.location(in: gesture.view))")
I think you can check the tap location that belongs imageView or not on the onTap function.
Like this:
func ontap(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: parentView)
if imageView.layer.frame.contains(point) {
print("ImageView frame is \(self.imageView.layer.visibleRect)")
print("Gesture occurred at \(point)")
}
}
As the layers don't update their frame/position etc, I needed to add the following in the image view subclass I wrote (FloatingImageView):
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let pres = self.layer.presentation()!
let suppt = self.convert(point, to: self.superview!)
let prespt = self.superview!.layer.convert(suppt, to: pres)
return super.hitTest(prespt, with: event)
}
I also moved the gesture recognizer to the parent view so there was only one GR at any time, and created a unique tag for each of the subviews being added. The handler looks like the following:
func onTap(gesture:UITapGestureRecognizer) {
let p = gesture.location(in: gesture.view)
let v = gesture.view?.hitTest(p, with: nil)
if let v = v as? FloatingImageView {
print("The tapped view was \(v.tag)")
}
}
where FloatingImageView is the UIImageView subclass.
This method was described in an iOS 10 book (as well as in WWDC), and works for iOS 9 as well. I am still evaluating UIViewPropertyAnimator based tap detection, so if you can give me an example of how to use UIViewPropertyAnimator to do the above, I will mark your answer as the correct one.
Using shinobi charts
Looking for examples how to add gesture recognizers (on touch up) to Tick Marks and schart annoations
I see the documentation for interacting with a series data series, but I need to add GestureRecognizers to tick marks and annotation events
I tried this for the tickMark/datapoint labels with no luck:
func sChart(chart: ShinobiChart!, alterTickMark tickMark: SChartTickMark!, beforeAddingToAxis axis: SChartAxis!) {
if let label = tickMark.tickLabel {
//added a gesture recognizer here but it didn't work
}
For the SchartAnnotations no idea how to go about adding one there
I think you're nearly there with labels. I found I just needed to set userInteractionEnabled = true e.g.
func sChart(chart: ShinobiChart!, alterTickMark tickMark: SChartTickMark!, beforeAddingToAxis axis: SChartAxis!) {
if let label = tickMark.tickLabel {
let tapRecognizer = UITapGestureRecognizer(target: self, action: "labelTapped")
tapRecognizer.numberOfTapsRequired = 1
label.addGestureRecognizer(tapRecognizer)
label.userInteractionEnabled = true
}
}
Annotations are a little trickier, as they're on a view below SChartCanvasOverlay (responsible for listening for gestures). This results in the gestures being 'swallowed' before they get to the annotation.
It is possible however, but you'll need to add a UITapGestureRecognizer to your chart and then loop through the chart's annotations to check whether the touch point was inside an annotation. E.g.:
In viewDidLoad:
let chartTapRecognizer = UITapGestureRecognizer(target: self, action: "annotationTapped:")
chartTapRecognizer.numberOfTapsRequired = 1
chart.addGestureRecognizer(chartTapRecognizer)
And then the annotationTapped function:
func annotationTapped(recognizer: UITapGestureRecognizer) {
var touchPoint: CGPoint?
// Grab the first annotation so we can grab its superview for later use
if let firstAnnotation = chart.getAnnotations().first as? UIView {
// Convert touch point to position on annotation's superview
let glView = firstAnnotation.superview!
touchPoint = recognizer.locationInView(glView)
}
if let touchPoint = touchPoint {
// Loop through the annotations
for item in chart.getAnnotations() {
let annotation: SChartAnnotation = item as SChartAnnotation
if (CGRectContainsPoint(annotation.frame, touchPoint as CGPoint)) {
chart.removeAnnotation(annotation)
}
}
}
}