How to change the label appearing at the top left corner that says "Cancel" when I open a modal view... I would like it to be a button with an image.
The label Cancel
is the default 'title' of a modally presented WKInterfaceController, which appears on the Apple Watch status bar.
It is not possible to hide the status bar, nor is it possible to display an image in the status bar, neither as part of this link nor to replace this link.
You can however set the title to a new string value. For instance, you might well want to replace Cancel
with Close
. There are four ways that you can set this title, which are outlined below. Ensure you read the Note at the bottom as likely only Option 1 will be acceptable in most circumstances.
You can set the title of the modally presented WKInterfaceController in Interface Builder. Simply set the Title attribute in the Attributes Inspector. Only a single static title can be set this way for each WKInterfaceController, of course, although it can be changed dynamically at runtime using any of the mechanisms outlined above.
You can set the title in the init method for the modally presented WKInterfaceController:
override init () {
super.init ()
self.setTitle("Close")
}
You can set the title directly in the awakeWithContext method of the modally presented WKInterfaceController:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.setTitle("Close")
}
You can pass the title to the modally presented WKInterfaceController using the context variable. In interface builder, set the identifier
in the Attributes Inspector of the controller to be presented modally. (In this example, it was set to "modalController".) You then present the controller by passing the desired title as the Context:
self.presentControllerWithName("modalController", context: "Close")
Then, in the modally presented controller:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.setTitle(context as? String)
}
The current 'intended behaviour' of WatchKit almost certainly means that only the first option will be seen as acceptable in most use cases. This is because currently, for the other three options you will initially see the default title for the view as it loads, which will then be replaced with the text you set using setTitle. awakeWithContext runs by design after the view has loaded, but even using setTitle in init does not avoid the initial display of the default title.
The first option outlined above replaces Cancel
with a new default title for the view. If you combine a custom Title in Interface builder with any of Options 2-4 below, you see exactly the same symptom (initial title then being replaced with your setTitle
), just with a different initial title.