You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中按钮标题切换异常:需点击两次才生效的问题求助

Fixing the Double-Tap Issue on Your Collection View Button

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:

  1. The code hits the if isSelected == false branch
  2. It calls fetchMyPosts() again (redundant, since you already loaded this data)
  3. Only then does it set isSelected = true and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:55:52