【问题标题】:Remove Programmatically Added UIButton删除以编程方式添加的 UIButton
【发布时间】:2015-09-01 19:14:11
【问题描述】:

在我的视图控制器的 viewDidLoad 中,我添加了一个按钮:

        let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
        tutorialButton.frame = CGRectMake(0, (UIScreen.mainScreen().bounds.size.height/4)*3, UIScreen.mainScreen().bounds.size.width, 20)
        tutorialButton.titleLabel?.textAlignment = NSTextAlignment.Center
        tutorialButton.backgroundColor = UIColor.clearColor()
        tutorialButton.setTitle("View Quick Tutorial", forState: UIControlState.Normal)
        tutorialButton.addTarget(self, action: "giveTutorial:", forControlEvents: UIControlEvents.TouchUpInside)

        self.view.addSubview(tutorialButton)

按钮出现在我想要的位置,并且该部分效果很好。但是在它达到目的并且我不再希望它可见之后,如何从视图中删除该按钮?我研究过它通常是这样完成的:

buttonName.removeFromSuperview

但是,当我输入 buttonName 时,它​​无法识别该按钮。我猜是因为没有 IBOutlet。那么我可以在一个方法中添加什么代码来删除这个按钮呢?

【问题讨论】:

  • 将按钮放入实例变量中,然后调用instanceVariable.removeFromSuperview()
  • 使tutorialButton 成为控制器类的成员。然后你可以使用self.tutorialButon.removeFromSuperview。如果您希望能够删除它,则需要保留对它的引用以便将其删除。

标签: ios swift uibutton iboutlet


【解决方案1】:

声明一个类变量(不是 IBOutlet)来保存按钮引用。

var tutorialButton : UIButton?

在代码中填充 button 并使用

删除
tutorialButton?.removeFromSuperview

【讨论】:

    【解决方案2】:

    原来我的问题不在于我输入了什么代码,而在于我在哪里输入了代码。因为我希望在加载时添加视图,所以我将整个代码块添加到我的 viewDidLoad。但是,这条线不属于那里:

    let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    

    通过在 viewDidLoad 中声明 tutorialButton,我导致它在 viewDidLoad 之外无法访问/引用。为了解决这个问题,我所要做的就是将该行移到 viewDidLoad 之外。

    let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ...
    

    如果您打算稍后通过 viewDidLoad 以外的方法编辑或删除视图,请注意这一点。现在我进行了更改,我可以将 removeFromSuperview 调用添加到 buttonPress 并且效果很好:

    tutorialButton?.removeFromSuperview
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多