Display ETA and estimated money option for my "Ride there with Uber" button - uber-api

I have integrated a "Ride there with Uber" button to my app. I feel, it would be more convenient for the users, if i displayed the ETA and estimated pricing for the destination. How may I achieve this? I am following this guide as of now : https://github.com/uber/rides-ios-sdk
It seems like I need, some kind of product ID to be able to achieve this. But how do i get it?
Made some progress, I got my self the product id, but it still doesn't work. Here is my current code:

Button will Deeplink into the Uber App and will simply open up the app. In order to see real-time fare estimates and pickup ETA information you will need to pass additional parameters to it. The Ride Request Button can accept optional parameters to pre-load some information into the ride request. You can see how to do it in the Uber documentation. Also this is explained here on the GitHub.

I got the solution ||
ViewController.swift
var button = RideRequestButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let builder = RideParametersBuilder()
let pickupLocation = CLLocation(latitude: 37.787654, longitude: -122.402760)
let dropoffLocation = CLLocation(latitude: 37.775200, longitude: -122.417587)
builder.pickupLocation = pickupLocation
builder.dropoffLocation = dropoffLocation
builder.dropoffNickname = "Somewhere"
builder.dropoffAddress = "123 Fake St."
var productID = ""
let ridesClient = RidesClient()
ridesClient.fetchProducts(pickupLocation: pickupLocation) { (product, response) in
productID = product[1].productID!
builder.productID = productID
}
ridesClient.fetchPriceEstimates(pickupLocation: pickupLocation, dropoffLocation: dropoffLocation) { (price, response) in
print(price[0].estimate!)
self.button.rideParameters = builder.build()
self.button.loadRideInformation()
}
button.center = self.view.center
self.view.addSubview(button)
}
Also, do make little change into UberRides->RideRequestButton.swift`
override public func setContent() {
super.setContent()
uberMetadataLabel.numberOfLines = 0
uberMetadataLabel.sizeToFit()`
and
private func setMultilineAttributedString(title: String, subtitle: String = "", surge: Bool = false) {
let metadataFont = UIFont(name: "HelveticaNeue-Regular", size: 10) ?? UIFont.systemFont(ofSize: 10)
and last one change width (+30) of uberMetadataLabel below like
override public func sizeThatFits(_ size: CGSize) -> CGSize
var width: CGFloat = 4*horizontalEdgePadding + imageLabelPadding + logoSize.width + titleSize.width+30
If any query please comment here

The issue is kind of funny and I think uber should change there documentation. You need to fetch products and price estimates and then loadRideInformation(). Guess what! the default button width is smaller than required. (Don't forget to add both the ClientID and ServerToken)
let pickupLocation = CLLocation(latitude:23.782221 , longitude:90.395263 )
let dropoffLocation = CLLocation(latitude: 23.8116404, longitude: 90.4279034)
let uberClient = RidesClient()
let builder = RideParametersBuilder()
let uberReqButton = RideRequestButton()
uberReqButton.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: uberReqButton.frame.height)
self.uberview.addSubview(uberReqButton)
SKActivityIndicator.show()
uberClient.fetchProducts(pickupLocation: pickupLocation, completion: { (Products, _) in
if (Products[0].productID != nil){
uberClient.fetchPriceEstimates(pickupLocation: pickupLocation, dropoffLocation: dropoffLocation) { (priceEstimates, Response) in
SKActivityIndicator.dismiss()// used for loading animation, ignore if not not needed
builder.pickupLocation = pickupLocation
builder.pickupAddress = "pickup Address"
builder.pickupNickname = "pickup nick"
builder.dropoffLocation = dropoffLocation
builder.dropoffAddress = "drop Address"
builder.dropoffNickname = "drop nick"
builder.productID = Products[0].productID
uberReqButton.rideParameters = builder.build()
DispatchQueue.main.async {
uberReqButton.loadRideInformation()
}
}
}
})

Related

GMUClusterRendererDelegate show marker iconview only when cluster is rendered and not before that swift 5

i am trying to create clusters in my google map. When i show clusters on map i want to show only the cluster count and when the cluster is clicked or zoom then only i want to show my Custom marker view.
Bu the marker view are already present before clustering and when i zoom in a cluster, the default pins are shown, which i dont want.
below is the code for clustering
for data in self.map_data {
//check if map data is on or off and show map data accordignly
let offerdata = data
let geocoder = CLGeocoder()
let strAddress = "\(offerdata.agent_street ?? "")"+" "+"\(offerdata.agent_city ?? "")"+" "+"\(offerdata.agent_zipcode ?? "")"
//MARK: GEOCODER FOR GETTING LAT LONG BASE ON ADDRESS
geocoder.geocodeAddressString(strAddress) {
placemarks, error in
let placemark = placemarks?.first
let lat = Double(placemark?.location?.coordinate.latitude ?? 0.00)
let lon = Double(placemark?.location?.coordinate.longitude ?? 0.00)
print("Lat: \(String(describing: lat)), Lon: \(String(describing: lon))")
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 5)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
marker.title = "\(offerdata.agent_firstname ?? "")"+" \(offerdata.agent_lastname ?? " ")"
marker.iconView?.backgroundColor = .lightGray
marker.userData = data
//amrut
// Clustering
let item = POIItem(position: CLLocationCoordinate2DMake(lat, lon), name: "marker.title" ?? "",data: data)
self.clusterManager.add(item)
//map info views
var image = UIImage()
var currency = String()
if data.currency == "AUD"{
currency = "$\(data.currency ?? "")"
}
else if data.currency == "EUR"{
currency = "€\(data.currency ?? "")"
}
else{
currency = "£\(data.currency ?? "")"
}
let amount = "\(data.offer_amount ?? "")".convertTo2Decimal+" "+currency
//create custom marker accordin to condtions
// "\(agent.offer_amount ?? "")".convertTo2Decimal+" "+"\(agent.currency ?? "AUD")"
if data.auto_approval_on_off == "ON"{
if (data.is_badge_display == "1") {
image = UIImage(named: "blueMarker.png") ?? UIImage()//blue
} else {
image = UIImage(named: "orangeMarker.png") ?? UIImage()//oranfge
}
}
else if (data.is_badge_display == "1") {
image = UIImage(named: "blueMarker.png") ?? UIImage()//blue
} else {
image = UIImage(named: "blackMarker.png") ?? UIImage()//black
}
let customMarker = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: 100, height: 40), image:image , lblText:amount)
// marker.iconView=customMarker
marker.map = self.MapView
self.MapView.camera = camera
}
}
and the same thing i do when in 'GMUClusterRendererDelegate willRenderMarker' delegate method and just uncomment the marker.iconView=customMarker
can anyone please help me what i need to be doing. It will be really helpful
Image for reference
Image for reference2
Two things i want:
1- show clustering for initial load without map icon views
2- show only map icon view and not the pins after cluster rendered/zoom
Please someone help me
I have a problem similar to this. The work around I came up with was to run the clearMarkers function and then re-add the entire array of markers back in using the addMarkers function
I'm still working on this so if I find a better answer I'll update

Google Maps iOS is not allowing custom map marker image

I am using the Google Maps SDK for iOS - https://developers.google.com/maps/documentation/ios-sdk/marker#use_the_markers_icon_property
Combined with the Maps SDK for iOS Utility Library https://developers.google.com/maps/documentation/ios-sdk/utility/kml-geojson#render-kml-data
I am trying to use the utility library to render a kml file on a map. It mostly works, however the custom icons for the markers are not loading. The markers with their titles, snippets, and locations all load correctly. The only thing that does not work is the custom icon for the marker.
Originally, I thought it was an issue with the utility library, so I spent some time trying to write my own code to go through the kml file and add the custom markers myself. However, before I got too far I noticed that even when I try to add a basic marker with a custom icon, I cannot. This led me to believe it was an issue not with the utility library but with the Maps SDK for iOS. I've tried moving the folder that the image is in, and making sure that the code can see the path to the images, but I cannot get it to work.
This is the code that I have in my project
let path = Bundle.main.path(forResource: testFile, ofType: "kml")
let url = URL(fileURLWithPath: path!)
let kmlParser = GMUKMLParser(url: url)
kmlParser.parse()
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: zoom)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.mapType = GMSMapViewType.terrain
mapView.isMyLocationEnabled = true
mapView.settings.zoomGestures = true
mapView.settings.myLocationButton = true
let renderer = GMUGeometryRenderer(map: mapView, geometries: kmlParser.placemarks, styles: kmlParser.styles, styleMaps: kmlParser.styleMaps)
renderer.render()
This also does not work
let position = CLLocationCoordinate2D(latitude: lat, longitude: long)
let marker = GMSMarker(position: position)
marker.title = "Test"
marker.icon = UIImage(named: "icon-1")
marker.map = mapView
Thanks in advance for any help
I haven't figured out why the utils library wasn't working, but I did come up with my own fix. It's horrible, but I can come back and make it better later after we've finished adding all the other necessary features to the app and can focus on cleaning up the code .
First, I made a new array of placemarks that had everything except the map markers. I then used this array of placemarks instead of kmlParser.placemarks, so that everything else could be added by the utility library.
//Removing markers without icons
var myIndex = 0
var removed = [GMUGeometryContainer]()
for mark in kmlParser.placemarks{
if(mark.geometry.type != "Point"){
removed.append(kmlParser.placemarks[myIndex])
}
myIndex += 1
}
let renderer = GMUGeometryRenderer(map: mapView, geometries: removed, styles: kmlParser.styles, styleMaps: kmlParser.styleMaps)
renderer.render()
After that, I made my own horrible horrible method that reads the kml file again, and only picks out the placemarks and styles for them and returns an array of Markers.
func addMarkers(fileName:String) -> [GMSMarker]{
var markers = [GMSMarker]()
if let path = Bundle.main.path(forResource: fileName, ofType: "kml"){
do{
let data = try String(contentsOfFile: path, encoding: .utf8)
let myStrings = data.components(separatedBy: .newlines)
var styleToIcon = [String: String]()
var lineNum = 0
for line in myStrings{
//Detecting new style that will be used in placemarks
if line.contains("Style id") && line.contains("normal") && !line.contains("line-"){
let newKey = String(line.split(separator: "\"")[1])
let newValue = String(myStrings[lineNum+4].split(separator: ">")[1].split(separator: "/")[1].split(separator: "<")[0])
styleToIcon[newKey] = newValue
}
//Detecting new placemark on map
else if(line.contains("<Placemark>") && !myStrings[lineNum+2].contains("#line")){
//Get name
var name = myStrings[lineNum+1].split(separator: ">")[1].split(separator: "<")[0]
//Sometimes name has weird CDATA field in it that needs to be removed
if(name.contains("![CDATA")){
name = name.split(separator: "[")[2].split(separator: "]")[0]
}
//Get snippet (description)
var snippet = myStrings[lineNum+2].split(separator: ">")[1].split(separator: "<")[0]
//Sometimes snippet has weird CDATA field in it that needs to be removed
if(snippet.contains("![CDATA")){
snippet = snippet.split(separator: "[")[2].split(separator: "]")[0]
}
//Get style
let style = String(myStrings[lineNum+3].split(separator: ">")[1].split(separator: "#")[0].split(separator: "<")[0] + "-normal")
//Get Coordinates
let coordStringSplit = myStrings[lineNum+6].split(separator: ",")
var lat = 0.0
var long = 0.0
if(coordStringSplit[0].contains("-")){
long = Double(coordStringSplit[0].split(separator: "-")[1])! * -1.0
}else{
long = Double(coordStringSplit[0])!
}
if(coordStringSplit[1].contains("-")){
lat = Double(coordStringSplit[1].split(separator: "-")[1])! * -1.0
}else{
lat = Double(coordStringSplit[1])!
}
//Create marker and add to list of markers
let position = CLLocationCoordinate2D(latitude: lat, longitude: long)
let marker = GMSMarker(position: position)
marker.title = String(name)
marker.snippet = String(snippet)
marker.icon = UIImage(named: styleToIcon[style]!)
markers.append(marker)
}
lineNum += 1
}
}catch{
print(error)
}
}
return markers
}
This is so heavily related to how my kml files look that I doubt it will help anyone else, but I thought I should post it just in case.
Now that we have that method, all we need to do is go back to where we were rendering all of the kml data and render those markers on the map
//Adding markers with icons
let newMarkers = addMarkers(fileName: courseName)
for mark in newMarkers{
mark.map = mapView
}
I also had to go through my kml files manually and fix some of the image names, but that wasn't a big deal. Even if the utility library worked I would need to do that because the utility library only does kml files and not kmz, so each kml file references the same folder for images and uses the same names for images. It's fine, only takes a few minutes per file. Would be nice if there was a kmz library but oh well.
Hopefully this helps someone else, and hopefully I can find the real solution soon (unless its a problem with the utility library in which case hopefully it's fixed soon).
//call method by passing ;
if userLocation.coordinate.latitude != 0.0 && userLocation.coordinate.longitude != 0.0
{
self.updateCurrentPositionMarker(currentLocation: CLLocation(latitude: userLocation.coordinate.latitude, longitude:userLocation.coordinate.longitude))
}
//methods
func updateCurrentPositionMarker(currentLocation: CLLocation) {
self.currentPositionMarker.map = nil
self.currentPositionMarker = GMSMarker(position: currentLocation.coordinate)
if self.imageDataUrl != ""
{
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude, zoom: 18.0)
self.mapView.camera = camera
//self.imageDataUrl == image to show
self.currentPositionMarker.iconView = self.drawImageWithProfilePic(urlString:self.imageDataUrl,image: UIImage.init(named: “backgroungImage”)!)
self.currentPositionMarker.zIndex = 1
}
self.currentPositionMarker.map = self.mapView
self.mapView.reloadInputViews()
}
func drawImageWithProfilePic(urlString:String, image: UIImage) -> UIImageView {
let imgView = UIImageView(image: image)
imgView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
let picImgView = UIImageView()
picImgView.sd_setImage(with:URL(string: urlString))
picImgView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
imgView.addSubview(picImgView)
picImgView.center.x = imgView.center.x
picImgView.center.y = imgView.center.y-10
picImgView.layer.cornerRadius = picImgView.frame.width/2
picImgView.clipsToBounds = true
imgView.setNeedsLayout()
picImgView.setNeedsLayout()
// let newImage = imageWithView(view: imgView)
// return newImage
return imgView
}

Not able to add Multiple Markers in GSMapView xCode Swift 3

I am trying to add multiple Markers on Googlemaps in my app.
In the viewcontrolller under viewDidLoad I am able to load the map and a single marker.
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("section_map", comment: "test")
let camera = GMSCameraPosition.camera(withLatitude: 48.7784, longitude:9.18121, zoom: 12)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
view = mapView
mapView.settings.myLocationButton = true
mapView.delegate = self
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 48.7784,longitude: 9.18121)
marker.title = "title"
marker.snippet = "snipple"
marker.icon = UIImage(named:"pin_you")
marker.map = mapView
mapData()
}
It call mapData() and from there is json file is generated
after parsing setPin is called to set the markers
func setPin(){
DispatchQueue.main.async {
for item in self.mapItems {
print (" \(item.name) \(item.marker) \(item.latitude) \(item.longitude)")
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
marker.title = item.name
marker.snippet = item.fulladdress
var iconImage: String
switch (item.marker){
case 1:
iconImage = "pin_silver"
case 2:
iconImage = "pin_blue"
case 3:
iconImage = "pin_gold"
case 6:
iconImage = "pin_you"
default:
iconImage = "pin_silver"
}
marker.icon = UIImage(named:iconImage)
marker.map = self.mapView
}
}
}
The pins are not shown.
The print in for item in self.mapItems shows
Position number A 1 48.76947562 9.15440351
Position number B 1 48.75716485 9.17081058
Position number C 1 48.81191625 9.22752149
Position number D 2 48.81192516 9.22766708
this means all the proper data is available.
However the map is there the one pin made in viewDidLoad
The Markers in function setPin are not shown or maybe not set.
Does any-one have an idea?
I have solved it in have changed the mapData(mapView: GMSMapView!) also for setPin(mapView: GMSMapView!)
func setpin(mapView: GMSMapView!){
DispatchQueue.main.async {
for item in self.mapItems {
print (" \(item.name) \(item.marker) \(item.latitude) \(item.longitude)")
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: item.latitude,longitude: item.longitude)
marker.title = item.name
marker.snippet = item.fulladdress
var iconImage: String
switch (item.marker){
case 1:
iconImage = "pin_silver"
case 2:
iconImage = "pin_blue"
case 3:
iconImage = "pin_gold"
case 6:
iconImage = "pin_you"
default:
iconImage = "pin_silver"
}
marker.icon = UIImage(named:iconImage)
marker.map = mapView
}
}
}
Clustering your markers, you can put a large number of markers on a map without making the map hard to read. The marker clustering utility helps you manage multiple markers at different zoom levels.
For the full code sample, see the ObjCDemoApp and SwiftDemoApp on GitHub.
To add a simple marker clusterer.
/// Point of Interest Item which implements the GMUClusterItem protocol.
class POIItem: NSObject, GMUClusterItem {
var position: CLLocationCoordinate2D
var name: String!
init(position: CLLocationCoordinate2D, name: String) {
self.position = position
self.name = name
}
}
The following code creates a cluster manager using the GMUNonHierarchicalDistanceBasedAlgorithm and the MUDefaultClusterRenderer that are included in the utility library:
class ViewController: UIViewController, GMUClusterManagerDelegate,
GMSMapViewDelegate {
private var mapView: GMSMapView!
private var clusterManager: GMUClusterManager!
override func viewDidLoad() {
super.viewDidLoad()
// Set up the cluster manager with the supplied icon generator and
// renderer.
let iconGenerator = GMUDefaultClusterIconGenerator()
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: mapView,
clusterIconGenerator: iconGenerator)
clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm,
renderer: renderer)
// Generate and add random items to the cluster manager.
generateClusterItems()
// Call cluster() after items have been added to perform the clustering
// and rendering on map.
clusterManager.cluster()
}
}
Feed your markers into the cluster as GMUClusterItem objects by calling clusterManager:addItem:. The following code randomly generates cluster items (POIs) within the scope of the map's camera, then feeds them to the cluster manager:
/// Randomly generates cluster items within some extent of the camera and
/// adds them to the cluster manager.
private func generateClusterItems() {
let extent = 0.2
for index in 1...kClusterItemCount {
let lat = kCameraLatitude + extent * randomScale()
let lng = kCameraLongitude + extent * randomScale()
let name = "Item \(index)"
let item =
POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name)
clusterManager.addItem(item)
}
}
/// Returns a random value between -1.0 and 1.0.
private func randomScale() -> Double {
return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0
}
Handle events on markers and clusters
class ViewController: UIViewController, GMUClusterManagerDelegate, GMSMapViewDelegate {
private var mapView: GMSMapView!
private var clusterManager: GMUClusterManager!
override func viewDidLoad() {
super.viewDidLoad()
// ... Rest of code omitted for easy reading.
// Register self to listen to both GMUClusterManagerDelegate and
// GMSMapViewDelegate events.
clusterManager.setDelegate(self, mapDelegate: self)
}
// MARK: - GMUClusterManagerDelegate
func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
let newCamera = GMSCameraPosition.cameraWithTarget(cluster.position,
zoom: mapView.camera.zoom + 1)
let update = GMSCameraUpdate.setCamera(newCamera)
mapView.moveCamera(update)
}
// MARK: - GMUMapViewDelegate
func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
if let poiItem = marker.userData as? POIItem {
NSLog("Did tap marker for cluster item \(poiItem.name)")
} else {
NSLog("Did tap a normal marker")
}
return false
}
}
For more Details please follow the Here

Set custom accessibilityIdentifier for GMSMarker

I use a Google Maps Api for maps and markers.
I enable accessibility for markers by setting: mapView.accessibilityElementsHidden = false
Now all my custom markers on map have accessibility ids like: myappname.GMSPlaceMarker_somenumbers, for example myappname.GMSPlaceMarker_0x600000170200.
How could i set a one accessibilityIdentifier for all pins, for example Map pin?
I already tried:
marker.accessibilityLabel = "Map pin" but it set label value, not id
marker.title = "Map pin" nothing changes
marker.setValue("Map pin", forKey: "accessibilityIdentifier") nothing changes
My marker is let marker = GMSPlaceMarker() where class GMSPlaceMarker: GMSMarker
try this,
func markPoints() {
var annotationCoord : CLLocationCoordinate2D = CLLocationCoordinate2D()
annotationCoord.latitude = (selectedLocation.latitude as NSString).doubleValue
annotationCoord.longitude = (selectedLocation.longitude as NSString).doubleValue
let annotationPoint: MKPointAnnotation = MKPointAnnotation()
annotationPoint.coordinate = annotationCoord
annotationPoint.title = selectedLocation.name
annotationPoint.subtitle = "Anand: 7348858742"
theMap.addAnnotation(annotationPoint)
}
If you are using swift 4 try this one,
var destionationMarker: GMSMarker!
func setupDriverMarker(coordinate: CLLocationCoordinate2D) {
destionationMarker = GMSMarker(position: coordinate)
for pin: GMSMarker in self.DestinationMarkerArray {
if pin.userData as! String == "drivermarker" {
pin.map = nil
}
}
destionationMarker.title = "Your Title"
destionationMarker.appearAnimation = GMSMarkerAnimation.pop
let images = #imageLiteral(resourceName: "ic_map_marker")
destionationMarker.icon = images
destionationMarker.userData = "drivermarker"
destionationMarker.opacity = 1
destionationMarker.map = journeyMapView
}
Implementing like this
DriverLocation = CLLocationCoordinate2D(latitude: 21.2362546, longitude: 72.8751862)
setupDriverMarker(coordinate: DriverLocation)
I had a similar issue as well, there is no accessibilityIdentifier for GMSMarker. What I did, setting either an accessibilityIdentifier to icon or iconView such as:
marker.icon?.accessibilityIdentifier = "something" or
marker.iconView?.accessibilityIdentifier = "something"

SystemStatusBar statusItem title being cut short on OS X

I am trying to display an OS X application statusItem in the System Status Bar and am having success with everything except the fact that the title is being cut off. I am initializing everything like so:
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func applicationDidFinishLaunching(aNotification: NSNotification) {
let icon = NSImage(named: "statusIcon")
icon?.template = true
statusItem.image = icon
statusItem.menu = statusMenu
statusItem.title = "This is a test title"
}
The problem is the statusItem.title is appearing like so:
As you can see the application next to mine (iStatMenuBar) is cutting off the title to my application (or something similar is happening)
If I comment out the icon for the statusItem, it works and shows the entire title but when I re-add the icon it cuts off again. Is there a way for the two (icon and title) to co exist? I have reviewed some Apple docs and may have missed a critical piece which explains this.
Thanks guys.
One option would be to assign a custom view to your statusBarItem and within that view's class override drawRect(dirtyRect: NSRect) e.g.
private var icon:StatusMenuView?
let bar = NSStatusBar.systemStatusBar()
item = bar.statusItemWithLength(-1)
self.icon = StatusMenuView()
item!.view = icon
and StatusMenuView might look like:
// This is an edited copy & paste from one of my personal projects so it might be missing some code
class StatusMenuView:NSView {
private(set) var image: NSImage
private let titleString:NSString = "really long title..."
init() {
icon = NSImage(named: "someImage")!
let myWideStatusBarItemFrame = CGRectMake(0, 0, 180.0, NSStatusBar.systemStatusBar().thickness)
super.init(frame.rect)
}
override func drawRect(dirtyRect: NSRect)
{
self.item.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: self.isSelected)
let size = self.image.size
let rect = CGRectMake(2, 2, size.width, size.height)
self.image.drawInRect(rect)
let titleRect = CGRectMake( 2 + size.width, dirtyRect.origin.y, 180.0 - size.width, size.height)
self.titleString.drawInRect(titleRect, withAttributes: nil)
}
}
Now, the above might change your event handling, you'll need to handle mouseDown in the StatusMenuView class.