I've created a custom callOutView, which seem to work fine. However i have problem with handling tap on the custom callOut view. I would like push to a specific viewController when it is selected. How can i achieve this?
below i've added my FBSingleClusterView, which is the custom MKAnnotationView and the bubbleView which is the custom callOutView. beside this i ofcourse have an viewController with a mapView.
FBSingleClusterView Variables
private var hitOutside:Bool = true
var preventDeselection:Bool {
return !hitOutside
}
FBSingleClusterView methods
override func setSelected(selected: Bool, animated: Bool) {
let calloutViewAdded = bubbleView?.superview != nil
if (selected || !selected && hitOutside) {
super.setSelected(selected, animated: animated)
}
self.superview?.bringSubviewToFront(self)
if (bubbleView == nil) {
bubbleView = BubbleView()
}
if (self.selected && !calloutViewAdded) {
bubbleView?.clipsToBounds = true
bubbleView?.layer.masksToBounds = true
self.addSubview(bubbleView!)
let discView = UIImageView()
discView.contentMode = UIViewContentMode.Center
discView.image = UIImage()
discView.image = UIImage(named: "Disclosure")
bubbleView?.contentView.addSubview(discView)
let nameLabel = UILabel()
nameLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
nameLabel.font = UIFont.systemFontOfSize(10)
nameLabel.textColor = UIColor.whiteColor()
nameLabel.text = companyString?.uppercaseString
bubbleView?.addSubview(nameLabel)
discView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(bubbleView!).offset(0)
make.height.equalTo(30)
make.width.equalTo(20)
make.right.equalTo(bubbleView!).offset(0)
}
nameLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(bubbleView!).offset(0)
make.left.equalTo(bubbleView!).offset(10)
make.height.equalTo(30)
make.right.equalTo(bubbleView!).offset(-20)
}
let nameLabelWidth = nameLabel.requiredWidth(companyString!.uppercaseString, font: UIFont.systemFontOfSize(10)) + 35
let bubbleHeight = 35 as CGFloat
bubbleView?.frame = CGRectMake((self.frame.width/2)-(nameLabelWidth/2), -bubbleHeight-2, nameLabelWidth, bubbleHeight)
}
if (!self.selected) {
bubbleView?.removeFromSuperview()
}
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
var hitView = super.hitTest(point, withEvent: event)
if let callout = bubbleView {
if (hitView == nil && self.selected) {
hitView = callout.hitTest(point, withEvent: event)
}
}
hitOutside = hitView == nil
return hitView;
}
bubbleView methods
override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let viewPoint = superview?.convertPoint(point, toView: self) ?? point
// let isInsideView = pointInside(viewPoint, withEvent: event)
let view = super.hitTest(viewPoint, withEvent: event)
return view
}
override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return CGRectContainsPoint(bounds, point)
}
}
Have you tried using instantiateViewControllerWithIdentifier? You can trigger this when tapping a button, in the viewDidLoad or in whatever other method you want it to trigger and push a new a viewController.
Firstly, set the "Storyboard ID" for the viewController in your storyboard. Like this:
Example:
Here's an example of how you can push to a new viewController when tapping a cell. As mentioned you can use this method in different functions to push to another viewController :
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let yourNewView = self.storyboard!.instantiateViewControllerWithIdentifier("yourStoryBoardID") as! ViewControllerYourePushingTo
self.presentViewController(yourNewView, animated: true, completion: nil)
}
In your case this is in the hitTest func.
I asked a similar question not too long ago. Here's the reference: Swift: Triggering TableViewCell to lead to a link in a UIWebView in another ViewController
Here's the link from Apple Dev: InstantiateViewControllerWithIdentifier
You can add gesture on custom annotation view in didselectannotation and navigate to other view controllor from gesture action
Related
I followed this answer to create a button that is part of a second window that is on top of all other windows. It works fine with 1 button because it allows only that one button to get touch events, ignores everything else inside the second window, but the main window underneath of it still receives all of it touch events.
// This comment is from #robmayoff's answer
// As I mentioned, I need to override pointInside(_:withEvent:) so that the window ignores touches outside the button:
var button: UIButton?
private override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
guard let button = button else { return false }
let buttonPoint = convertPoint(point, toView: button)
return button.pointInside(buttonPoint, withEvent: event)
}
The way I have it now inside the SecondWindow, I can receive touch events for the cancelButton but the other buttons get ignored along with everything else. The question is how do I receive touch events for the other buttons inside the second window but still ignore everything else?
The Second UIWindow. This is what I tried but it didn't work:
class SecondWindow: UIWindow {
var cancelButton: UIButton?
var postButton: UIButton? // I need this to also receive touch events
var reloadButton: UIButton? // I need this to also receive touch events
init() {
super.init(frame: UIScreen.main.bounds)
backgroundColor = nil
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let cancelButton = cancelButton {
let cancelButtonPoint = convert(point, to: cancelButton)
return cancelButton.point(inside: cancelButtonPoint, with: event)
}
if let postButton = postButton {
let postButtonPoint = convert(point, to: postButton)
return postButton.point(inside: postButtonPoint, with: event)
}
if let reloadButton = reloadButton {
let reloadButtonPoint = convert(point, to: reloadButton)
return reloadButton.point(inside: reloadButtonPoint, with: event)
}
return false
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
guard let safeHitView = hitView else { return nil }
if safeHitView.isKind(of: SecondController.self) { return nil }
return safeHitView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The vc with the buttons:
class SecondController: UIViewController {
lazy var cancelButton: UIButton = { ... }()
lazy var postButton: UIButton = { ... }()
lazy var reloadButton: UIButton = { ... }()
let window = SecondWindow()
init() {
super.init(nibName: nil, bundle: nil)
window.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
window.cancelButton = cancelButton
window.postButton = postButton
window.reloadButton = reloadButton
window.isHidden = false
window.backgroundColor = .clear
window.rootViewController = self
window.windowLevel = UIWindow.Level.normal
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
// Anchors for buttons
}
}
I check to see if the point touched is inside the receiver (whichever button is touched). If it is it returns true then the touch is acknowledged and the button responds, if it's not it does nothing and skips to the next button, checks there and repeats the process until the last button and the same process is repeated.
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let cancelButton = cancelButton, let postButton = postButton, let reloadButton = reloadButton else {
return false
}
let cancelButtonPoint = convert(point, to: cancelButton)
let cancelBool = cameraButton.point(inside: cameraButtonPoint, with: event)
if cancelBool {
return cancelButton.point(inside: cancelButtonPoint, with: event)
}
let postButtonPoint = convert(point, to: postButton)
let postBool = postButton.point(inside: postButtonPoint, with: event)
if postBool {
return postButton.point(inside: postButtonPoint, with: event)
}
let reloadButtonPoint = convert(point, to: reloadButton)
return reloadButton.point(inside: reloadsButtonPoint, with: event)
}
I have a view that is with the black border and it has two different views on it. And these views are overlapping in a small area. And each of them has own UITapGestureRecognizer. When I tap each item's discrete area, the action of that item is triggered. But when I tap the common area, only the second view's action is triggered. I want that both actions have to be triggered. How can I achieve this? Here is my code:
class ViewController: UIViewController {
#IBOutlet weak var view1: UIView!
#IBOutlet weak var view2: UIView!
#IBOutlet weak var outerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
outerView.layer.borderWidth = 2.0
outerView.layer.borderColor = UIColor.black.cgColor
view1.layer.borderWidth = 2.0
view1.layer.borderColor = UIColor.red.cgColor
view2.layer.borderWidth = 2.0
view2.layer.borderColor = UIColor.blue.cgColor
self.initialize()
}
private func initialize(){
let tapGesture1 = UITapGestureRecognizer(target: self, action: #selector(detectTap1(_:)))
let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(detectTap2(_:)))
self.view1.addGestureRecognizer(tapGesture1)
self.view2.addGestureRecognizer(tapGesture2)
}
#objc func detectTap1(_ gesture : UITapGestureRecognizer) {
print("detectTap1")
}
#objc func detectTap2(_ gesture : UITapGestureRecognizer) {
print("detectTap2")
}
}
Kindly share your suggestions.
For this problem i have found this solution, maybe is not the best solution but it works, i will look for further improvements anyway
I had subclassed UIGestureRecognizer class
Updated
import UIKit
import UIKit.UIGestureRecognizerSubclass
class CustomGestureRecognizer: UIGestureRecognizer {
var anotherGestureRecognizer : CustomGestureRecognizer?
private var touchBeganSended : Bool = false
private var touchLocation : CGPoint?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
if let validTouch = touches.first?.location(in: self.view) {
if (self.view!.point(inside: validTouch, with: event)) {
if(!touchBeganSended) {
touchBeganSended = true
touchLocation = validTouch
anotherGestureRecognizer?.touchesBegan(touches, with: event)
state = .recognized
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
if let validTouch = touches.first?.location(in: self.view) {
if (self.view!.point(inside: validTouch, with: event)) {
if(touchBeganSended) {
touchBeganSended = false
anotherGestureRecognizer?.touchesEnded(touches, with: event)
state = .recognized
}
}
}
}
override func location(in view: UIView?) -> CGPoint {
if let desiredView = view {
if(desiredView == self.view) {
return touchLocation ?? CGPoint(x: 0, y: 0)
} else {
return super.location(in: view)
}
} else {
return super.location(in: view)
}
}
}
Updated
then you need to modify your initialize() method to this one, with the last update you don't need to take into account which view is on top on view hierarchy
private func initialize(){
let tapGesture1 = CustomGestureRecognizer(target: self, action: #selector(detectTap1(_:)))
let tapGesture2 = CustomGestureRecognizer(target: self, action: #selector(detectTap2(_:)))
tapGesture1.cancelsTouchesInView = true
tapGesture1.delegate = self
tapGesture2.cancelsTouchesInView = true
tapGesture2.delegate = self
self.view1.addGestureRecognizer(tapGesture1)
tapGesture1.anotherGestureRecognizer = tapGesture2
tapGesture2.anotherGestureRecognizer = tapGesture1
self.view2.addGestureRecognizer(tapGesture2)
}
this works as you can see here
Try the following:
private func initialize(){
let tapGesture1 = UITapGestureRecognizer(target: self, action: #selector(detectTap1(_:)))
let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(detectTap2(_:)))
tapGesture1.cancelsTouchesInView = false
tapGesture2.cancelsTouchesInView = false
self.view1.addGestureRecognizer(tapGesture1)
self.view2.addGestureRecognizer(tapGesture2)
}
When you set
gesture.cancelsTouchesInView = false
it propagates the gesture to the views underneath.
Try to implement this UIGestureRecognizerDelegate method:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
...
...
private func initialize() {
...
gesture1.delegate = self
gesture2.delegate = self
...
}
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
// its up to you
//guard otherGestureRecognizer == yourAnotherGesture else { return false }
return true
}
So I have a simple UIPopoverPresentationController that displays some content.
User can dismiss it by tapping anywhere on the screen (default popover behaviour).
I want the popover to be dismissed if the user does any kind of tap or gesture on the screen. Preferably drag gesture.
Any idea if this is possible? And how?
try using touchesBegan:withEvent method
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
if touch.view == self.view {
self.dismiss()
} else {
return
}
}
}
VC is the view presented in the popover.
in the presentViewController:animated:completion: block
[self presentViewController:vc animated:YES completion:^{
UIView *v1 = vc.view.superview.superview.superview;
for (UIView* vx in v1.subviews) {
Class dimmingViewClass = NSClassFromString(#"UIDimmingView");
if ([vx isKindOfClass:[dimmingViewClass class]])
{
UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(closePopoverOnSwipe)];
[vx addGestureRecognizer:pan];
}
}
}];
you have a UIDimmingView that holds the tap gesture that will close. just add to it. I am using the Class dimmingViewClass = NSClassFromString(#"UIDimmingView"); to avoid making direct use of undocumented APIs. I have not tried yet to send this hack to apple, but will try next week. I hope it will pass. But I tested this and it did call my selector.
I resolved this problem using custom view:
typealias Handler = (() -> Void)?
final class InteractionView: UIView {
var dismissHandler: Handler = nil
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismissHandler?()
}
}
In the viewDidAppear configure this view and add to popover containerView:
fileprivate func configureInteractionView() {
let interactionView = InteractionView(frame: self.view.bounds)
self.popoverPresentationController?.containerView?.addSubview(interactionView)
interactionView.backgroundColor = .clear
interactionView.isUserInteractionEnabled = true
interactionView.dismissHandler = { [weak self] in
self?.hide()
}
}
fileprivate func hide() {
self.dismiss(animated: true, completion: nil)
}
my solution for this problem.
for example if you create a class UIViewController named MyPopoverViewController to present PopViewController.
then in the viewDidLoad() or viewWillAppear(_ animated:) Method add two GestureRecognizer as follows:
protocal MyPopoverControllerDelegate {
func shouldDismissPopover()
}
class MyPopoverViewController : UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// back trace to root view, if it is a UIWindows, add PanGestureRecognizer
// and LongPressGestureRecognizer, to dismiss this PopoverViewController
for c in sequence(first: self.view, next: { $0.superview}) {
if let w = c as? UIWindow {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(dismissPopover(gesture:)))
w.addGestureRecognizer(panGestureRecognizer)
let longTapGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(dismissPopover(gesture:)))
w.addGestureRecognizer(longTapGestureRecognizer)
}
}
#objc private func dismissPopover(gesture: UIGestureRecognizer) {
delegate?.shouldDismissPopover()
}
}
then in your main ViewController, which this PopOverViewController presents, implements the Method of the Protocol.
extension YourMainViewController: MyPopoverControllerDelegate {
func shouldDismissPopover() {
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
}
I have this splash view and I'm having problems with use3dtouch because I'm having an error telling me that splashview has no instance member 'use3dtouch'. Here is the code.
Here is an image of the error
The error
import Foundation
import UIKit
class VPSplashView : UIView {
var vp = VPSplashView()
private lazy var __once: () = {
if VPSplashView.traitCollection.forceTouchCapability == UIForceTouchCapability.unavailable
{
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(VPSplashView.longPressed(_:)))
self.addGestureRecognizer(longPressRecognizer)
VPSplashView.use3DTouch = false
} else {
VPSplashView.use3DTouch = true
}
}()
static func addSplashTo(_ view : UIView, menuDelegate: MenuDelegate) -> VPSplashView{
let splashView = VPSplashView(view: view)
splashView.backgroundColor = UIColor.clear
splashView.isExclusiveTouch = true
if (view.isKind(of: UIScrollView.classForCoder())){
(view as! UIScrollView).canCancelContentTouches = false
}
splashView.menu?.delegate = menuDelegate
return splashView
}
// MARK: Initialization
var menu : VPSplashMenu?
fileprivate var use3DTouch : Bool = true
var onceToken: Int = 0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(view: UIView){
super.init(frame:view.bounds)
view.addSubview(self)
self.menu = VPSplashMenu.init(center: self.center)
}
func setDataSource(_ source: MenuDataSource!){
self.menu?.dataSource = source
}
override func layoutSubviews() {
super.layoutSubviews()
self.superview?.bringSubview(toFront: self)
if (self.superview != nil){
self.setup()
}
}
fileprivate func setup(){
_ = self.__once;
}
// MARK: Long Press Handling
func longPressed(_ sender: UILongPressGestureRecognizer)
{
switch sender.state {
case .began:
let centerPoint = sender.location(in: self)
menu?.movedTo(centerPoint)
menu?.showAt(self)
menu?.squash()
case .ended:
menu?.cancelTap()
menu?.removeFromSuperview()
case .changed:
let centerPoint = sender.location(in: self)
menu?.handleTap((menu?.convert(centerPoint, from: self))!)
default:
menu?.removeFromSuperview()
}
}
// MARK: Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if (use3DTouch == true){
var centerPoint : CGPoint = CGPoint.zero
for touch in touches {
centerPoint = touch.location(in: self)
menu?.movedTo(centerPoint)
menu?.showAt(self)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if (use3DTouch == true){
for touch in touches {
let centerPoint = touch.location(in: self)
if (menu?.shown == false){
menu?.movedTo(centerPoint)
if (touch.force > minimalForceToSquash){
menu?.squash()
}
} else {
menu?.handleTap((menu?.convert(centerPoint, from: self))!)
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if (use3DTouch == true){
menu?.hide()
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if (use3DTouch){
menu?.hide()
}
}
}
Your added code has clarified some important things to write an answer...
traitCollection is an instance property which is declared in UITraitEnvironment, where UIView conforms to
use3DTouch is an instance property which is declared in VPSplashView explicitly
longPressed(_:) is an instance method which is declared in VPSplashView explicitly
The third is not critical in this case, but the first two are clearly related to the error message you have gotten: Instance member cannot be used.
When you access to instance members (in this case, instance properties), you need to prefix an instance reference before .memberName, not a class name.
In your case, self seems to be an appropriate instance:
private lazy var __once: () = {
//###
if self.traitCollection.forceTouchCapability == UIForceTouchCapability.unavailable
{
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressed(_:)))
self.addGestureRecognizer(longPressRecognizer)
//###
self.use3DTouch = false
} else {
//###
self.use3DTouch = true
}
}()
But you are doing things in far more complex way than needed, so you may need some more fixes.
One critical thing is this line:
var vp = VPSplashView()
This may cause some runtime issue (even if you have solved some compile-time issue) and vp is not used. Better remove it.
I need a completely customizable callout for for MKAnnotation. I have subclassed MKAnnotationView and an UIView. My code:
class CustomAnnotationView: MKAnnotationView {
class var reuseIdentifier:String {
return "CustomAnnotationView"
}
private var calloutView:MapPinCallOut?
private var hitOutside:Bool = true
var preventDeselection:Bool {
return !hitOutside
}
convenience init(annotation:MKAnnotation!) {
self.init(annotation: annotation, reuseIdentifier: CustomAnnotationView.reuseIdentifier)
//false?
canShowCallout = true;
}
override func setSelected(selected: Bool, animated: Bool) {
let calloutViewAdded = calloutView?.superview != nil
if (selected || !selected && hitOutside) {
super.setSelected(selected, animated: animated)
}
self.superview?.bringSubviewToFront(self)
if (calloutView == nil) {
calloutView = MapPinCallOut()
}
if (self.selected && !calloutViewAdded) {
addSubview(calloutView!)
}
if (!self.selected) {
calloutView?.removeFromSuperview()
}
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
var hitView = super.hitTest(point, withEvent: event)
if let callout = calloutView {
if (hitView == nil && self.selected) {
hitView = callout.hitTest(point, withEvent: event)
}
}
hitOutside = hitView == nil
return hitView;
}
}
Here is my UIView:
class MapPinCallOut: UIView {
override func hitTest(var point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let viewPoint = superview?.convertPoint(point, toView: self) ?? point
let isInsideView = pointInside(viewPoint, withEvent: event)
var view = super.hitTest(viewPoint, withEvent: event)
return view
}
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return CGRectContainsPoint(bounds, point)
}
}
I have also created a nib file and changed the file's owner to "MapPinCallOut"
Then in my viewDidLoad of my viewController, I am adding a pin like this:
let location = CLLocationCoordinate2D(
latitude: 25.0336,
longitude: 121.5650
)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
let string = "title"
let annotation = CustomAnnotation(location: location, title: string, subtitle: string)
mapView.addAnnotation(annotation)
and then in my viewForAnnotation function:
var pinView: CustomAnnotationView = CustomAnnotationView()
pinView.annotation = annotation
pinView.canShowCallout = true
return pinView
After all that, I ran my code and when I select the annotation, the callout does appear but it is still the standard annotation. What am I missing to create my own custom callout view?
Set pinView.canShowCallout to false in your viewForAnnotation. That may help you out.