点击按钮切换背景图片报错:unrecognized selector问题原因排查请求
Hey there, let's break down why you're seeing this error and how to fix it quickly!
What's Causing the Error?
The error message ViewController oButton: unrecognized selector sent to instance ... tells us exactly what's wrong: your app is trying to call a method named oButton on your ViewController instance, but there's no such method in your code.
Looking at your code, oButton is actually an IBOutlet (the button itself), not an action method. This means you accidentally linked your button's tap event to the wrong thing in Storyboard/XIB.
Step-by-Step Fix
- Open your Storyboard or XIB file where the
oButtonis placed. - Right-click on the
oButtonto bring up the connections menu, or switch to the Connections Inspector (the arrow icon in the right-side panel). - Look under the Sent Events section (usually
Touch Up Insideis the default tap event). You'll see it's currently linked tooButton(the IBOutlet) instead of youroButtonActionmethod. - Delete that wrong connection (click the small "x" next to the connection line), then re-link the tap event to the
oButtonActionmethod. You can do this by dragging from the event to your ViewController class in the code editor, or selectingoButtonActionfrom the dropdown in the Connections Inspector.
A Small Code Cleanup (Not the Error Cause, But Good Practice)
Your setBackgroundImage line has an extra pair of parentheses that aren't needed. It won't break anything, but cleaning it up makes the code cleaner:
oButton.setBackgroundImage(UIImage(named: "plus"), for: .normal)
Quick Double-Check for Future Functionality
Once you fix the selector error, make sure:
- The image named
plusis properly added to your project'sAssets.xcassetsfolder. - The image name matches exactly (iOS is case-sensitive, so
Pluswon't work if your file is namedplus).
内容的提问来源于stack exchange,提问作者Artem Derut

