Добавление двух кнопок в SKScene: для нижней кнопки нет действий - PullRequest
0 голосов
/ 30 сентября 2018

Я создаю SKScene с двумя кнопками.

import UIKit
import SpriteKit

class IntroScene: SKScene {
  override func didMove(to view: SKView) {
    // BUTTON PLAY GAME
    let btnPlay = BtnPlay(normalTexture: defaultBtnTexture,
                          selectedTexture: selectedBtnTexture,
                          disabledTexture: nil)
    btnPlay.size = CGSize(width: 250, height: 75)
    btnPlay.position = CGPoint(x: frame.midX,y: frame.height/3*1)
    btnPlay.name = "btnPlay"
    btnPlay.setButtonAction(target: self, triggerEvent: .TouchUpInside, action: #selector(IntroScene.goToGameScene))
    print("BUTTON PLAY FRAME 1 ",btnPlay.frame)
    addChild(btnPlay)

    // BUTTON 'FIND PLAYERS'
    let btnFindPlayers = BtnFindPlayers(normalTexture: defaultBtnTexture,
                                        selectedTexture: selectedBtnTexture,
                                        disabledTexture: nil)

    btnFindPlayers.size = CGSize(width: 250, height: 75)
    btnFindPlayers.position = CGPoint(x: self.frame.midX,y: self.frame.height/3*2)
    btnFindPlayers.name = "btnFindPlayers"
    btnFindPlayers.setButtonAction(target: self, triggerEvent: .TouchUpInside, action: #selector(IntroScene.goToConnectVC))
    print("BUTTON FIND FRAME 1 ",btnFindPlayers.frame)
    addChild(btnFindPlayers)
  }

  @objc func goToGameScene() {
    print("Go to Game Scene")
  }

  @objc func goToConnectVC() {
    print("Go to Connect VC")
  }
}

Это пользовательский класс для одной из кнопок.Другой класс использует аналогичные методы:

import SpriteKit

class BtnPlay: SKSpriteNode {
  enum BtnPlayType: Int {
    case TouchUpInside = 1,TouchDown, TouchUp
  }

  var disabledTexture: SKTexture?
  var defaultTexture: SKTexture
  var selectedTexture: SKTexture
  var label: SKLabelNode

  var isEnabled: Bool = true {
    didSet {
        if disabledTexture != nil {
            texture = isEnabled ? defaultTexture : disabledTexture
        }
    }
  }

  var isSelected: Bool = false {
    didSet {
        texture = isSelected ? selectedTexture : defaultTexture
    }
  }

required init(coder: NSCoder) {
    fatalError("NSCoding not supported")
}

init(normalTexture defaultTexture: SKTexture!, selectedTexture:SKTexture!, disabledTexture: SKTexture?) {
    self.defaultTexture = defaultTexture
    self.selectedTexture = selectedTexture
    self.disabledTexture = disabledTexture
    self.label = SKLabelNode(fontNamed: "Helvetica");
    self.label.text = "PLAY"

    super.init(texture: defaultTexture, color: UIColor.white, size: defaultTexture.size())
    isUserInteractionEnabled = true

    self.label.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center;
    self.label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center;
    addChild(self.label)

    let bugFixLayerNode = SKSpriteNode(texture: nil, color: UIColor.clear, size: defaultTexture.size())
    bugFixLayerNode.position = self.position
    addChild(bugFixLayerNode)
}

var actionTouchUpInside: Selector?
var actionTouchUp: Selector?
var actionTouchDown: Selector?
weak var targetTouchUpInside: AnyObject?
weak var targetTouchUp: AnyObject?
weak var targetTouchDown: AnyObject?

func setButtonAction(target: AnyObject, triggerEvent event:BtnPlayType, action:Selector) {
    switch (event) {
    case .TouchUpInside:
        targetTouchUpInside = target
        actionTouchUpInside = action
    case .TouchDown:
        targetTouchDown = target
        actionTouchDown = action
    case .TouchUp:
        targetTouchUp = target
        actionTouchUp = action
    }
}

func setButtonLabel(title: NSString, font: String, fontSize: CGFloat) {
    self.label.text = title as String
    self.label.fontSize = fontSize
    self.label.fontName = font
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !isEnabled { return }

    isSelected = true

    if (targetTouchDown != nil && targetTouchDown!.responds(to: actionTouchDown)) {
        UIApplication.shared.sendAction(actionTouchDown!, to: targetTouchDown, from: self, for: nil)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    if !isEnabled { return }

    let touch: AnyObject! = touches.first
    let touchLocation = touch.location(in: parent!)

    if (frame.contains(touchLocation)) {
        isSelected = true
    } else {
        isSelected = false
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !isEnabled { return }

    isSelected = false

    if (targetTouchUpInside != nil && targetTouchUpInside!.responds(to: actionTouchUpInside!)) {
        let touch: AnyObject! = touches.first
        let touchLocation = touch.location(in: parent!)

        if (frame.contains(touchLocation)) {
            UIApplication.shared.sendAction(actionTouchUpInside!, to: targetTouchUpInside, from: self, for: nil)
        }

        print("BUTTON PLAY FRAME ",frame)
        print("BUTTON PLAY TOUCHES ",touchLocation)
    }

    if (targetTouchUp != nil && targetTouchUp!.responds(to: actionTouchUp!)) {
        UIApplication.shared.sendAction(actionTouchUp!, to: targetTouchUp, from: self, for: nil)
    }
  }
}

Сцена и кнопки создаются просто отлично.Кнопка «Найти игроков» создана сверху.Проблема в том, что когда я нажимаю на нижнюю кнопку («Play»), ничего не происходит.Виновник стучит по экрану.Всякий раз, когда я нажимаю где-нибудь на экране, за исключением самой нижней его части, выбирается верхняя кнопка.Итак, если я нажимаю на нижнюю кнопку, я все еще вижу на консоли:

BUTTON FIND FRAME  (387.0, 474.5, 250.0, 75.0)
BUTTON FIND TOUCHES  (409.139404296875, 563.622131347656)

Похоже, что рамка верхней кнопки намного больше, чем сама кнопка, и накладывает нижнюю кнопку, не позволяя мне нажимать

Понятия не имею, почему это происходит.

Буду очень признателен, если кто-то сможет помочь.

...