MKAnnotation - Cannot assign to property: 'title' is a get-only property - mapkit

How do I resolve this build issue - I'm just trying to create an annotation for mapkit:
ERROR: "MKAnnotation - Cannot assign to property: 'title' is a get-only property"
import UIKit
import MapKit
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Annotations
var annotation:MKAnnotation
annotation.title = "test" // ** ISSUE IS HERE **
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Notes:
- Have downloaded latest version of XCode
- is this to do with Swift 2.0?
-

MKAnnotation requires that the object inherit from NSObjectProtocol. To do that, you should have your class inherit from NSObject. You should declare your properties to match those of the MKAnnotation protocol.
Example:
class MapPin : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
// Annotations
var annotation:MapPin
annotation.title = "test"
}

Related

Objective C not presenting argument labels for Swift convenience init

I have a UIBarButtonItem subclass, "NavBarButtonItem", defined in Swift 3.0 but am not sure if I've set up the convenience initializer properly. This initializer seems works fine in other Swift classes:
let nextBarButtonItem = NavBarButtonItem.init(self, "Next", #selector(pressedNextButton))
However, in Obj-C, Xcode presents me with the following (it's missing argument labels):
self.nextButton = [NavBarButtonItem alloc] init:<#(id<NavBarButtonDelegate> _Nonnull)#> :<#(NSString * _Nonnull)#> :<#(SEL _Nonnull)#>
and I've completed it with:
self.nextButton = [[NavBarButtonItem alloc] init:rvc :2 :#"Next" :#selector(doneButtonTapped:)];
I've not set up initializers in Swift before so suspect that there might be something wrong but the app compiles. Here's the Swift subclass:
MyViewController.swift
// this file contains other classes that precede subclass NavBarButtonItem
..
#objc protocol NavBarButtonDelegate {
func pressedNextButton()
}
#objc class NavBarButtonItem: UIBarButtonItem
{
private var delegate: NavBarButtonDelegate?
init(_ delegate: NavBarButtonDelegate){
self.delegate = delegate
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(_ delegate: NavBarButtonDelegate, _ title: String, _ selector: Selector)
{
self.init(delegate, wtfProperty)
self.title = title
self.action = selector
}
}

How set title of a WKInterfaceButton?

I'm trying to change the text of a button once it is pressed however it doesn't work. Am i missing something?
i've been trying to figure my problem for hours.
any help would be appreciated.
h. file
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
#interface InterfaceController : WKInterfaceController
{
IBOutlet WKInterfaceButton*playpausebtn;
}
-(IBAction)play;
#end
m. file
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
#interface InterfaceController() <WCSessionDelegate>
#end
#implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Configure interface objects here.
}
- (void)willActivate {
[super willActivate];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
- (void)didDeactivate {
// This method is called when watch view controller is no longer visible
[super didDeactivate];
}
-(IBAction)play{
[playpausebtn setTitle:#"sleep"];
}
It is working fine in Swift-3 Xcode-8.1 .
// InterfaceController.swift
// WatchKit Extension
import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController,WCSessionDelegate {
#IBOutlet var textLabel: WKInterfaceLabel!
var session:WCSession?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
checkSupportOfSession()
changeAttributeOfText()
}
#IBOutlet var buttonOutlet: WKInterfaceButton!
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func checkSupportOfSession() {
if( WCSession.isSupported() ) {
self.session = WCSession.default()
self.session?.delegate = self
self.session?.activate()
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("session")
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
let message:String = message["textIndex"] as! String
textLabel.setText(message)
print(message)
}
func changeAttributeOfText() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let font = UIFont.boldSystemFont(ofSize: 12)
let attributes:Dictionary = [NSParagraphStyleAttributeName:paragraphStyle , NSFontAttributeName:font ]
let attributeString:NSAttributedString = NSAttributedString(string: "HELLO", attributes: attributes)
textLabel.setAttributedText(attributeString)
}
//Change the ButtonTitle after click
#IBAction func buttonClicked() {
buttonOutlet.setTitle("textNew")
}}
Demo App

What is equivalent of id<type> in Swift?

I have two delegates like this:
protocol MyFirstDelegate {
func change(value: int)
}
protocol MySecondDelegate {
weak var delegate: MyFirstDelegate?
}
Those protocols are implemented in two customized UIViewControllers:
class MyFirstViewController: UIViewController, MyFirstDelegate {
...
}
class MySecondViewController: UIViewController, MySecondDelegate {
...
}
The first UI view controller will push second UI view controller by using a segue.
In my first UI view controller class I have the following codes to prepare segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if let vc = (segue.destinationViewController) as? MySecondViewController {
vc.delegate = self
}
}
The above codes compile without any problem. However, I think that the first UI controller has knowledge about the next view controller class. I prefer to pass delegate like this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if var vc = (segue.destinationViewController) as? MySecondDelegate {
vc.delegate = self
}
}
I got compiling error:
Cannot assign to property: "vc" is immutable.
It seems that as to a concrete UI view controller is OK, but not to a protocol. Any explanation and solution to this?
By the way, in Objective-C, this can be done like this:
id<NSObject, MySecondDelegate> vc = segue.destinationViewController;
vc.delegate = self;
I could not find a way in swift to define a variable like
let vc: AnyObject<type>? // like id<type>
UPDATES
As #David_Berry solution, it works if I mark protocol as class. The above codes are actually simplified ones. I am in the middle of converting my ObjC codes to Swift. Therefore, I have to mark protocols as objc:
#objc protocol MyFirstDelegate : class {
func change(value: int)
}
#objc protocol MySecondDelegate {
weak var delegate: MyFirstDelegate?
}
with #objc, I still get the same compiling error.
Well, I finally managed to get your example to compile, you have a LOT of inconsistencies. The key to your actual problem, I think, is requiring that the protocols be class protocols:
protocol XXX : class { }
Says that only types that are classes can be declared to implement XXX.
But, I'm really not sure that's your problem, there were so many other changes required (you spelled MySecondDelegate at least two ways, MySecondViewController at least two ways, etc.
The compiling example is:
// This protocol has to be class so that delegate can be weak
protocol MyFirstDelegate : class {
func change(value: Int)
}
protocol MySecondDelegate {
weak var delegate: MyFirstDelegate? { get set }
}
class MyFirstViewController: UIViewController, MyFirstDelegate {
func change(value: Int) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if var vc = (segue.destinationViewController) as? MySecondDelegate {
vc.delegate = self
}
}
}
class MySecondViewController: UIViewController, MySecondDelegate {
weak var delegate : MyFirstDelegate?
}
As for your question, there is no swift synonym to the objective-C syntax id<Protocol> or Class<Protocol> There are multiple duplicates to that issue that offer alternatives.

How to invoke [self new] in Swift

Here is an UIView extension written in ObjectiveC to easily create view for using Auto-layout:
+(id)autolayoutView
{
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
it invokes [self new] so any subclass of UIView can use this method. How can I achieve this in Swift?
OK, this appears to be the solution. The type must have a required initializer with the correct parameter list (in this case no parameters).
class SubView: UIView {
override required init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class func autolayoutView() -> UIView {
var view = self()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}
}
Though both Carrl and Gregory Higley are right with there solutions, including thr remark about the fact that self() needs to use a required init i wanted to post a more general example:
class Human {
var gender = String()
required init() {
self.gender = "any"
}
class func newHuman() -> Human {
return self()
}
}
class Man : Human {
required init() {
super.init()
self.gender = "male"
}
}
var someMan = Man.newHuman()
println(someMan.gender) // male
Inspired by Gregory Higley, i think the solution is here:
extension UIView{
class func autolayoutView() -> UIView {
var view = self()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}
}
Update for Swift2.1:
extension UIView{
class func autolayoutView() -> UIView {
let view = self.init()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
}

Unwrap UIWindow twice from AppDelegate in Swift

To Get the rootViewController in Objective-c you can use the below line of code
[[[UIApplication sharedApplication] delegate] window].rootViewController
I tried to do the same in swift
UIApplication.sharedApplication().delegate?.window?.rootViewController
But I got this error
'UIWindow?' does not have a member named 'rootViewController'
And the suggestion says that you have to unwrap UIWindow twice UIWindow?? to be
UIApplication.sharedApplication().delegate?.window??.rootViewController
My Question is: Why do I need to unwrap the window twice ?
.
.
I have looked in the API and found that
protocol UIApplicationDelegate : NSObjectProtocol {
optional var window: UIWindow? { get set }
}
The window has one optional
class UIWindow : UIView {
var rootViewController: UIViewController?
}
Also the rootViewController has one optional
.
.
I thought may be because UIWindow in UIApplicationDelegate protocol has optional and UIWindow? so I tried the below in Playground
#objc protocol MyApplicationDelegate {
optional var myWindow: MyWindow? { get set }
}
class MyWindow : NSObject {
var rootViewController: Int?
init(number: Int) {
rootViewController = number
}
}
class MyAppDelegate: MyApplicationDelegate {
var myWindow: MyWindow?
init() {
myWindow = MyWindow(number: 5)
}
}
let myDelegate = MyAppDelegate()
println(myDelegate.myWindow?.rootViewController)
However I can get myWindow with one optional and can successfully log '5'
What am I missing here?
Well; I found the problem with my example
In my example I'm creating object from MyAppDelegate directly which will sure have myWindow property as I'm defining it
Changing the example to be the following
#objc protocol MyApplicationDelegate {
optional var myWindow: MyWindow? { get set }
}
class MyWindow : NSObject {
var rootViewController: Int?
init(number: Int) {
rootViewController = number
}
}
class MyAppDelegate: MyApplicationDelegate {
var myWindow: MyWindow?
init() {
myWindow = MyWindow(number: 5)
}
}
class MyApplication: NSObject {
var myDelegate: MyApplicationDelegate
override init() {
myDelegate = MyAppDelegate()
}
}
let myApplication = MyApplication()
println(myApplication.myDelegate.myWindow??.rootViewController)
I needed to add another class MyApplication that has a property conform toMyApplicationDelegate
So I was able to use myWindow?? first unwrapping for the optional part in the protocol and second one is for the optional declaration in the variable UIWindow?