@@ -94,33 +94,34 @@ class ViewController: UIViewController {
94
94
b. setTitle ( " Favorite Pep Boy: " , for: . normal)
95
95
b. sizeToFit ( )
96
96
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
+ }
98
118
b. showsMenuAsPrimaryAction = true
99
119
self . view. addSubview ( b)
100
120
default : break
101
121
}
102
122
103
123
}
104
124
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
- }
124
125
125
126
deinit {
126
127
print ( " farewell " )
0 commit comments