#ios #swift
#iOS #swift
Вопрос:
Я попытался создать кнопку в своей ячейке для моего UITableView. Я использовал этот код
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.dataSource = self
let currentLastItem = food[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as UITableViewCell
let btn = UIButton(type: UIButtonType.custom) as UIButton
btn.backgroundColor = UIColor.red
btn.setTitle(currentLastItem.name as String, for: UIControlState.normal)
btn.frame = CGRect(x: 15, y: 0, width: 300, height: 30)
btn.addTarget(self, action: Selector(("buttonPressed:")), for: UIControlEvents.touchUpInside)
btn.tag = indexPath.row
cell.contentView.addSubview(btn)
return cell
}
@objc func buttonPressed(sender:UIButton!)
{
let buttonRow = sender.tag
print("button is Pressed")
print("Clicked Button Row is" ,buttonRow)
}
Он не выдавал мне ошибку ни при его компиляции, ни при переходе к просмотру моей таблицы, а только при нажатии на нее.
Вот ошибка:
2019-03-14 22:52:18.239124 0800 QRCodeReader[1635:35763] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2019-03-14 22:53:40.452471 0800 QRCodeReader[1635:35763] -[QRCodeReader.FoodsViewController buttonPressed:]: unrecognized selector sent to instance 0x7fa2f8636ae0
2019-03-14 22:53:40.463165 0800 QRCodeReader[1635:35763] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[QRCodeReader.FoodsViewController buttonPressed:]: unrecognized selector sent to instance 0x7fa2f8636ae0'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e35f1bb __exceptionPreprocess 331
1 libobjc.A.dylib 0x000000010c336735 objc_exception_throw 48
2 CoreFoundation 0x000000010e37df44 -[NSObject(NSObject) doesNotRecognizeSelector:] 132
3 UIKitCore 0x0000000117dbeb4a -[UIResponder doesNotRecognizeSelector:] 287
4 CoreFoundation 0x000000010e363ed6 ___forwarding___ 1446
5 CoreFoundation 0x000000010e365da8 _CF_forwarding_prep_0 120
6 UIKitCore 0x0000000117d91ecb -[UIApplication sendAction:to:from:forEvent:] 83
7 UIKitCore 0x00000001177cd0bd -[UIControl sendAction:to:forEvent:] 67
8 UIKitCore 0x00000001177cd3da -[UIControl _sendActionsForEvents:withEvent:] 450
9 UIKitCore 0x00000001177cc31e -[UIControl touchesEnded:withEvent:] 583
10 UIKitCore 0x0000000117965018 _UIGestureEnvironmentSortAndSendDelayedTouches 5387
11 UIKitCore 0x000000011795efd1 _UIGestureEnvironmentUpdate 1506
12 UIKitCore 0x000000011795e9ad -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] 478
13 UIKitCore 0x000000011795e71d -[UIGestureEnvironment _updateForEvent:window:] 200
14 UIKitCore 0x0000000117dce78a -[UIWindow sendEvent:] 4058
15 UIKitCore 0x0000000117dac394 -[UIApplication sendEvent:] 352
16 UIKitCore 0x0000000117e815a9 __dispatchPreprocessedEventFromEventQueue 3054
17 UIKitCore 0x0000000117e841cb __handleEventQueueInternal 5948
18 CoreFoundation 0x000000010e2c4721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 17
19 CoreFoundation 0x000000010e2c3f93 __CFRunLoopDoSources0 243
20 CoreFoundation 0x000000010e2be63f __CFRunLoopRun 1263
21 CoreFoundation 0x000000010e2bde11 CFRunLoopRunSpecific 625
22 GraphicsServices 0x0000000112b441dd GSEventRunModal 62
23 UIKitCore 0x0000000117d9081d UIApplicationMain 140
24 QRCodeReader 0x000000010b9e25c4 main 68
25 libdyld.dylib 0x000000010f75c575 start 1
)
libc abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Кстати, что вообще такое lldb?
Комментарии:
1. Вместо
Selector(("buttonPressed:"))
используйте#selector(buttonPressed(_:)
.2. Где реализован метод buttonPressed: ? Как он объявлен? «нераспознанный селектор, отправленный в экземпляр» — это хорошо известная ошибка.
3. LLDB расшифровывается как L ow L evel D e b ugger. Смотрите больше на этом веб-сайте , объясняющем, что это такое, и в этой статье на Medium , описывающей, как его использовать.
4. Спасибо, Джордж. Когда я использовал ваше решение, оно просто выдало мне сообщение «Использование неразрешенного идентификатора ‘buttonPressed'»
5. @EdwardTrain Тогда эта функция не существует. Отредактируйте вопрос и покажите, как создается функция, например:
func myFunc()
(основная часть не нужна). Кроме того, убедитесь, что функция вызвана из правильной области. Xcode в любом случае должен выполнить автозаполнение функции.
Ответ №1:
Селекторы
Просто измените Selector(("buttonPressed:"))
на #selector(buttonPressed)
. Убедитесь, что селектор существует в классе, в котором вы находитесь (но вы можете делегировать и т.д.), И Xcode должен автоматически выполнить это за вас.
LLDB
Кроме того, LLDB расшифровывается как Low Level Debugger. Смотрите больше на этом веб-сайте, объясняющем, что это такое, и в этой статье на Medium, описывающей, как его использовать.
Ответ №2:
По-видимому, вы неправильно вызываете селектор, просто используйте приведенный ниже код:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.dataSource = self
let currentLastItem = food[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as UITableViewCell
let btn = UIButton(type: UIButtonType.custom) as UIButton
btn.backgroundColor = UIColor.red
btn.setTitle(currentLastItem.name as String, for: UIControlState.normal)
btn.frame = CGRect(x: 15, y: 0, width: 300, height: 30)
btn.addTarget(self, action: #selector(buttonPressed(_:), for: UIControlEvents.touchUpInside)
btn.tag = indexPath.row
cell.contentView.addSubview(btn)
return cell
}
@objc func buttonPressed(sender : UIButton )
{
let buttonRow = sender.tag
print("button is Pressed")
print("Clicked Button Row is: (buttonRow)")
}