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

Swift开发真心话大冒险App如何避免点击按钮后UILabel重叠显示

问题原因

你每次点击按钮都会新建一个UILabel实例并添加到视图中,旧标签没有被移除,才会出现堆叠的情况。最推荐的优化方案是复用同一个标签,不要每次点击都创建新标签,性能更好也更容易维护。

修改方案

步骤说明

  • 将展示内容的UILabel声明为ViewController的全局存储属性,仅初始化一次
  • 点击按钮时仅修改标签的text属性,不需要重复添加到视图
  • 顺便修复原代码中重复添加dareButton的冗余逻辑

完整修改后代码

import UIKit
import PlaygroundSupport

public class ViewController: UIViewController {
    // 全局复用的内容标签,声明为类属性
    private let contentLabel: UILabel = {
        let lbl = UILabel(frame: CGRect(x:95 , y:100, width: 325, height: 500))
        lbl.textColor = #colorLiteral(red: 0.6313725709915161, green: 0.6470588445663452, blue: 0.9058823585510254, alpha: 1.0)
        lbl.numberOfLines = 6
        return lbl
    }()

    public override func loadView() {
        super.loadView()
        let view = UIView()
        view.backgroundColor = .red
        self.view = view
        // 提前把复用的标签添加到视图上
        view.addSubview(contentLabel)
        
        //dare button
        let dareButton = UIButton(frame: CGRect(x:300, y: 500, width: 100, height: 69))
        dareButton.layer.cornerRadius = 10
        dareButton.backgroundColor = #colorLiteral(red: 0.6352941393852234, green: 0.6470588445663452, blue: 0.886274516582489, alpha: 1.0)
        dareButton.setTitle("dare", for: UIControl.State.normal)
        dareButton.addTarget(self, action: #selector(dareButtonDidTap), for: .touchDown)
        view.addSubview(dareButton)
    }
    @objc
    private func dareButtonDidTap() {
        // 仅更新文本即可,不需要新建标签
        contentLabel.text = daresEng.randomElement()
    }
}

// 测试用示例内容,可替换为你自己的题目库
let daresEng = ["做10个深蹲", "给最近联系的第一个人发一句我想你了", "模仿表情包做对应动作"]

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = ViewController()

临时替代方案(不推荐)

如果你不想调整现有结构,也可以每次新建标签前先移除之前的旧标签,在dareButtonDidTap开头加一行过滤移除代码即可:

@objc
private func dareButtonDidTap() {
    // 移除视图上所有旧的UILabel
    view.subviews.filter { $0 is UILabel }.forEach { $0.removeFromSuperview() }
    // 原有创建标签的逻辑保持不变
    let lbl = UILabel(frame: CGRect(x:95 , y:100, width: 325, height: 500))
    lbl.text = daresEng.randomElement()
    lbl.textColor = #colorLiteral(red: 0.6313725709915161, green: 0.6470588445663452, blue: 0.9058823585510254, alpha: 1.0)
    lbl.numberOfLines = 6
    view.addSubview(lbl)
}

内容的提问来源于stack exchange,提问作者user16854458

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:54:03