Skip to content

Commit 8108405

Browse files
committed
revise the example to make the menu dynamic on tap
1 parent 81f71da commit 8108405

File tree

2 files changed

+22
-21
lines changed

2 files changed

+22
-21
lines changed

bk2ch12p595NewButtons/NewButtons/Base.lproj/Main.storyboard

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
7676
</view>
7777
<navigationItem key="navigationItem" id="1mi-Ho-ukj">
78-
<barButtonItem key="rightBarButtonItem" title="Item" id="Isi-EM-mga">
78+
<barButtonItem key="rightBarButtonItem" title="Push" id="Isi-EM-mga">
7979
<connections>
8080
<segue destination="BYZ-38-t0r" kind="show" id="saX-p6-Y0E"/>
8181
</connections>

bk2ch12p595NewButtons/NewButtons/ViewController.swift

+21-20
Original file line numberDiff line numberDiff line change
@@ -94,33 +94,34 @@ class ViewController: UIViewController {
9494
b.setTitle("Favorite Pep Boy:", for: .normal)
9595
b.sizeToFit()
9696
b.frame.origin = CGPoint(50,200)
97-
self.rebuildMenuForButton(b)
97+
// "dynamic" menu, formed at the moment the user taps the button
98+
b.menu = UIMenu() // so that we have a menu to start with
99+
b.addAction(for: .menuActionTriggered) { action in
100+
guard let b = action.sender as? UIButton else { return }
101+
func boyAction(for name: String) -> UIAction {
102+
let image : UIImage? =
103+
name == self.currentFavorite ?
104+
UIImage(systemName: "checkmark") :
105+
nil
106+
return UIAction(title: name, image: image) { [weak self] action in
107+
self?.currentFavorite = action.title
108+
b.setTitle("Favorite Pep Boy: \(name)", for: .normal)
109+
b.sizeToFit()
110+
}
111+
}
112+
b.menu = UIMenu(title: "", children: [
113+
boyAction(for: "Manny"),
114+
boyAction(for: "Moe"),
115+
boyAction(for: "Jack")
116+
])
117+
}
98118
b.showsMenuAsPrimaryAction = true
99119
self.view.addSubview(b)
100120
default: break
101121
}
102122

103123
}
104124

105-
func rebuildMenuForButton(_ b: UIButton) {
106-
func boyAction(for name: String) -> UIAction {
107-
let image : UIImage? =
108-
name == self.currentFavorite ?
109-
UIImage(systemName: "checkmark") :
110-
nil
111-
return UIAction(title: name, image: image) { [weak self] action in
112-
self?.currentFavorite = action.title
113-
self?.rebuildMenuForButton(b)
114-
b.setTitle("Favorite Pep Boy: \(name)", for: .normal)
115-
b.sizeToFit()
116-
}
117-
}
118-
b.menu = UIMenu(title: "", children: [
119-
boyAction(for: "Manny"),
120-
boyAction(for: "Moe"),
121-
boyAction(for: "Jack")
122-
])
123-
}
124125

125126
deinit {
126127
print("farewell")

0 commit comments

Comments
 (0)