Swift中按钮标题切换异常:需点击两次才生效的问题求助
Hey there! I see exactly what's going on here. Let's break down why that button needs two taps to behave as expected, and how to fix it while keeping your viewDidLoad data fetch intact.
The Root Cause
When you call fetchMyPosts() in viewDidLoad, you're correctly loading your "My post" data—but your isSelected variable stays set to its default false value, and you don't update the button's title to match the loaded state.
So when you first tap the button:
- The code hits the
if isSelected == falsebranch - It calls
fetchMyPosts()again (redundant, since you already loaded this data) - Only then does it set
isSelected = trueand update the button title
That's why the first tap feels like it does nothing—you're just reloading the same data and syncing the state after the fact. The second tap finally triggers the switch to "your post" because isSelected is now true.
The Fix
All you need to do is sync your button's title and isSelected state right after you fetch the initial data in viewDidLoad. Here's the adjusted code:
var isSelected: Bool = false override func viewDidLoad() { super.viewDidLoad() // Load initial data first fetchMyPosts() // Sync button state to match the loaded data mostLiked.setTitle("My post", for: .normal) isSelected = true } @IBAction func myPosts(_ sender: UIButton) { if isSelected == false { mostLiked.setTitle("My post", for: .normal) fetchMyPosts() isSelected = true } else { mostLiked.setTitle("your post", for: .normal) fetchYourPosts() isSelected = false } }
Bonus Optimization (Optional)
To make this cleaner, you could use toggle() for the boolean state and extract the title strings to constants, which makes the code more readable and less error-prone:
// Define constants to avoid hardcoding titles private let myPostTitle = "My post" private let yourPostTitle = "your post" var isShowingMyPosts: Bool = false override func viewDidLoad() { super.viewDidLoad() fetchMyPosts() mostLiked.setTitle(myPostTitle, for: .normal) isShowingMyPosts = true } @IBAction func togglePosts(_ sender: UIButton) { isShowingMyPosts.toggle() if isShowingMyPosts { mostLiked.setTitle(myPostTitle, for: .normal) fetchMyPosts() } else { mostLiked.setTitle(yourPostTitle, for: .normal) fetchYourPosts() } }
Either version will resolve the double-tap issue while keeping your initial data load in viewDidLoad.
内容的提问来源于stack exchange,提问作者aaron

