簡體   English   中英

自定義 UIButton 不顯示

[英]Custom UIButton doesn't show up

我正在制作游戲,一切正常。 但是我制作的這個自定義按鈕似乎有問題:

let button = UIButton(type: UIButtonType.Custom) as UIButton
let image = UIImage(named: "bluePlayButton")
button.setImage(image, forState: UIControlState.Normal)
button.frame = CGRectMake(self.size.width/2, self.size.height * 0.15, 300, 200)
button.layer.zPosition = 1

self.view?.addSubview(button)

當我運行應用程序時,按鈕沒有出現。 我的代碼有什么問題,是否缺少某些內容?

我目前正在將 UI 元素集成到 sprite-kit 場景中,我不得不說這有點棘手。 如果您能給我提供有關該類其他元素的更多信息,是UIView還是SKScene (SKView) 或SKNode 當混合這兩種方法時,這真的很痛苦。

但是根據您提供的信息,我可以告訴您我遇到了同樣的問題,並且我解決了更改在 SKScene 上添加 UI 元素的方法。 在它出現在viewDidLoad之前,但我應該在viewDidAppear上這樣做。

示例(目標-C):

  • iCarousel是一個 UI 元素(不是 SKView 或 SKNode)。

`

-(void)didMoveToView:(SKView *)view {
//Your code but in Objective-C
UIButton * button  = UIButton
UIButton * button  = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage * image = [UIImage imageNamed:@"bluePlayButton"];
[button setImage:image forState:UIControlStateNormal];
[button setFrame:CGRectMake(self.size.width/2, self.size.height * 0.15, 300, 200)];
button.layer.zPosition=1;
[self.view addSubView:button];
}

`

  • 另外,仔細檢查按鈕的 zPosition 和其他元素。

  • 確保使用調試器正確加載圖像。 即使使用擴展名 (.png),也可能會發生一些事情來防止這種情況發生。 (正如@matt 在評論中所建議的那樣)

  • 強烈建議避免將 UIKit 元素與 Sprite-Kit 元素混合。

  • 如果這不能解決您的問題,請提供更多信息;)

編輯:另一個示例,說明如何在 Sprite-Kit 中執行對應於 UIButton 的操作(最簡單的方法)。

(剛剛取自這個問題 - 在 SKScene 中設置按鈕

您可以使用 SKSpriteNode 作為您的按鈕,然后當用戶觸摸時,檢查該節點是否被觸摸。 使用 SKSpriteNode 的 name 屬性來標識節點:

//fire button
- (SKSpriteNode *)fireButtonNode
{
    SKSpriteNode *fireNode = [SKSpriteNode spriteNodeWithImageNamed:@"fireButton.png"];
    fireNode.position = CGPointMake(fireButtonX,fireButtonY);
    fireNode.name = @"fireButtonNode";//how the node is identified later
    fireNode.zPosition = 1.0;
    return fireNode;
}

將節點添加到您的場景中:

[self addChild: [self fireButtonNode]];

處理接觸:

//handle touch events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    //if fire button touched, bring the rain
    if ([node.name isEqualToString:@"fireButtonNode"]) {
         //do whatever...
    }
}

暫無
暫無

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

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