簡體   English   中英

刪除以編程方式添加UIButton

[英]Remove Programmatically Added UIButton

在我的視圖控制器的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。 那么我可以在一個方法中使用哪些代碼來刪除此按鈕?

聲明一個類變量(不是IBOutlet)來保存按鈕引用。

var tutorialButton : UIButton?

在代碼中填充button並刪除

tutorialButton?.removeFromSuperview

我的問題原來不是我鍵入的代碼,而是我輸入的代碼。 因為我希望在加載時添加視圖,所以我將整個代碼塊添加到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM