Custom Button Not Working in Swift - swift

I have a UIViewController, a Custum UIView, and a GameController. The CustumUiView is layered on top of the UIViewController and I need to seperate out the views to track clicks on the UIView. I have a custom button in the Custum UIView "Interface View" that is registering the click, but the receiver in the GameController or the UIViewController (tried both) are not registering the clicks.
Code follows and help is appreciated.
Interface View
class InterfaceView: UIView {
var resetButton: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
resetButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
resetButton.setImage(UIImage(named: "reset"), for: UIControlState())
addSubview(resetButton)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// let touches through and only catch the ones on buttons
let hitView = super.hitTest(point, with: event)
if hitView is UIButton {
print("Captured Hit") // Stack Overflow Note: This is working.
return hitView
}
return nil
}
}
Game Controller:
class GameController
{
var interface: InterfaceView!
{
didSet
{
interface.resetButton.addTarget(self, action: #selector (GameController.reset), for: .touchUpInside)
}
#objc func reset(sender: UIButton!)
{
print("button pressed")
}
}
UIViewController:
class GameViewController: UIViewController
{
fileprivate let controller: GameController
#IBOutlet weak var GameView: UIView!
init(_ coder: NSCoder? = nil)
{
// Logic Goes Here
controller = GameController()
if let coder = coder
{
super.init(coder: coder)!
} else
{
super.init(nibName: nil, bundle: nil)
}
}
required convenience init(coder: NSCoder)
{
self.init(coder)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first as UITouch?
{
let point = touch.preciseLocation(in: GameView)
if (touch.view == GameView)
{
print("Do stuff")
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first
{
let point = touch.preciseLocation(in: GameView)
if (touch.view == GameView)
{
print("Do other stuff")
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
print("Reset Stuff")
}

Resolved by in GameViewController, using didSet to set the target and selector for the button press and then using a method in GameViewController to call a method within GameController.
#IBOutlet weak var interface: InterfaceView!
{
didSet
{
interface.resetButton.addTarget(self, action: #selector (GameViewController.reset), for: .touchUpInside)
}
}

Related

Why does my closure property on a SKLabelNode subclass become nil?

I have the following SKLabelNode subclass:
class ButtonNode: SKLabelNode {
// The only reason this is optional is because of the required init() method.
private var buttonAction: (() -> Void)?
init(_ text: String, action: #escaping () -> Void) {
self.buttonAction = action
// Initialise the button label node.
super.init(fontNamed: "Futura")
self.isUserInteractionEnabled = true
self.text = text
self.fontColor = SKColor.white
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first?.location(in: self) != nil {
self.buttonAction?()
}
}
}
I then instantiate the ButtonNode using:
let button = ButtonNode("Label", action: { print("Action called") })
This doesn't work as I expect it to (the action is never called). Upon investigating I discovered that:
In my intialiser the buttonAction property is not nil
In the touchesBegan method, the buttonAction property is nil
Why does the buttonAction property get set to nil?

spritekit make childnode not touchable

I have a menu button (skSpriteNode) and a small play icon inside this sprite
mainButton.addChild (playIcon)
mainButton.name = "xyz"
addchild (mainButton)
ok, I gave the button the name to check if a sprite with this name is touched.
when I touch the icon child inside the button, the touchedNode.name is nil. I set isUserInteractionEnabled = false for the icon child. I want to pass the touch to the parent. how can I do this.
for touch in touches {
let location = touch.location(in: self)
let touchedNode = self.atPoint(location)
if (touchedNode.name != nil) {
print ("node \(touchedNode.name!)")
} else {
continue
}
}
You have to implement touchesBegan in a subclass of SKSpriteNode and to set its isUserInteractionEnabled = true, in order to accept and process the touches for that particular node (button).
import SpriteKit
protocol ButtonDelegate:class {
func printButtonsName(name:String?)
}
class Button : SKSpriteNode{
weak var delegate:ButtonDelegate?
init(name:String){
super.init(texture: nil, color: .purple, size: CGSize(width: 250, height: 250))
self.name = name
self.isUserInteractionEnabled = true
let icon = SKSpriteNode(color: .white, size: CGSize(width:100, height:100))
addChild(icon)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.printButtonsName(name: self.name)
}
}
class GameScene: SKScene, ButtonDelegate {
override func didMove(to view: SKView) {
let button = Button(name:"xyz")
button.delegate = self
button.position = CGPoint(x: frame.midX - 50.0, y: frame.midY)
addChild(button)
}
func printButtonsName(name: String?) {
if let buttonName = name {
print("Pressed button : \(buttonName) ")
}
}
}
Now, this button will swallow the touches and the icon sprite will be ignored.
I just modified the code from one of my answers to make an example specific to your needs, but you can read, in that link, about whole thing more in detail if interested.
I implemented the button Touchbegan and tried to implement a subclass for a slider with a background and the child thumb inside the slider. I added the sliderDelegate Protocoll in my GameScene. the down touch is ok, but I didn't get the moved in
import Foundation
import SpriteKit
protocol SliderDelegate:class {
func touchesBeganSKSpriteNodeSlider(name:String?, location: CGPoint?)
func touchesMovedSKSpriteNodeSlider(name:String?, location: CGPoint?)
func touchesEndedSKSpriteNodeSlider(name:String?, location: CGPoint?)
}
class SKSpriteNodeSlider : SKSpriteNode{
weak var delegate:SliderDelegate?
init(imageNamed: String){
// super.init(imageNamed: imageNamed)
let texture = SKTexture(imageNamed: imageNamed)
super.init(texture: texture, color: .white, size: texture.size())
// self.name = name
self.isUserInteractionEnabled = true
// let icon = SKSpriteNode(color: .white, size: CGSize(width:100, height:100))
// addChild(icon)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// for touch in touches {
if let touch = touches.first {
let loc = touch.location(in: self)
delegate?.touchesBeganSKSpriteNodeSlider(name: self.name, location: loc)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print ("touchesMoved")
// for touch in touches {
if let touch = touches.first {
let loc = touch.location(in: self)
delegate?.touchesMovedSKSpriteNodeSlider(name: self.name, location: loc)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let loc = touch.location(in: self)
delegate?.touchesEndedSKSpriteNodeSlider(name: self.name, location: loc)
}
}
}

Swift 3: How do I pinch to scale and rotate UIImageView?

I am really struggling to find tutorials online as well as already answered questions (I have tried them and they don't seem to work). I have a UIImageView that I have in the centre of my view. I am currently able to tap and drag this wherever I want on screen. I want to be able to pinch to scale and rotate this view. How do I achieve this? I have tried the code for rotation below but it doesn't seem to work? Any help will be a massive help and marked as answer. Thank you guys.
import UIKit
class DraggableImage: UIImageView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.backgroundColor = .blue
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.backgroundColor = .green
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: superview)
center = CGPoint(x: position.x, y: position.y)
}
}
}
class CVController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotateAction(sender:)))
firstImageView.addGestureRecognizer(rotateGesture)
setupViews()
}
func rotateAction(sender: UIRotationGestureRecognizer) {
let rotatePoint = sender.location(in: view)
let firstImageView = view.hitTest(rotatePoint, with: nil)
firstImageView?.transform = (firstImageView?.transform.rotated(by: sender.rotation))!
sender.rotation = 0
}
let firstImageView: DraggableImage = {
let iv = DraggableImage()
iv.backgroundColor = .red
iv.isUserInteractionEnabled = true
return iv
}()
func setupViews() {
view.addSubview(firstImageView)
let firstImageWidth: CGFloat = 50
let firstImageHeight: CGFloat = 50
firstImageView.frame = CGRect(x: (view.frame.width / 2) - firstImageWidth / 2, y: (view.frame.height / 2) - firstImageWidth / 2, width: firstImageWidth, height: firstImageHeight)
}
}
You have a some problems in your code. First you need to add the UIGestureRecognizerDelegate to your view controller and make it your gesture recognizer delegate. You need also to implement shouldRecognizeSimultaneously method and return true. Second when applying the scale you need to save the transform when the pinch begins and apply the scale in top of it:
class DraggableImageView: UIImageView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
backgroundColor = .blue
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
backgroundColor = .green
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let position = touches.first?.location(in: superview){
center = position
}
}
}
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var identity = CGAffineTransform.identity
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupViews()
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(scale))
let rotationGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotate))
pinchGesture.delegate = self
rotationGesture.delegate = self
view.addGestureRecognizer(pinchGesture)
view.addGestureRecognizer(rotationGesture)
}
let firstImageView: DraggableImageView = {
let iv = DraggableImageView()
iv.backgroundColor = .red
iv.isUserInteractionEnabled = true
return iv
}()
func setupViews() {
view.addSubview(firstImageView)
let firstImageWidth: CGFloat = 50
let firstImageHeight: CGFloat = 50
firstImageView.frame = CGRect(x: view.frame.midX - firstImageWidth / 2, y: view.frame.midY - firstImageWidth / 2, width: firstImageWidth, height: firstImageHeight)
}
#objc func scale(_ gesture: UIPinchGestureRecognizer) {
switch gesture.state {
case .began:
identity = firstImageView.transform
case .changed,.ended:
firstImageView.transform = identity.scaledBy(x: gesture.scale, y: gesture.scale)
case .cancelled:
break
default:
break
}
}
#objc func rotate(_ gesture: UIRotationGestureRecognizer) {
firstImageView.transform = firstImageView.transform.rotated(by: gesture.rotation)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}

Why is deinit not called until UIView is added to parent again?

I have a UIView that am adding to a UIViewController and am generally testing de-initialization to make sure I am doing things right. But when I don't set the variable in my viewController to nil and only use .removeFromSuperView() , the deinit() method in UIView won't be called until I add the UIView another time then its called. But if I use removeFromSuperView() and set the variable to nil then deinit() is called right away. Why is that?
Here's UIView() class:
class TestView: UIView {
override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
print("init is happneing")
}
deinit {
print("de init is happneing")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here's the parent ViewController :
class MyViewController: UIViewController {
var tstview : TestView?
//adding the UIView by tapping on a button
#IBAction func addView(_ sender: UIButton) {
let test = TestView()
tstview = test
tstview?.frame = CGRect(x: 50, y: 60, width: self.view.frame.width-100, height: self.view.frame.height-200)
tstview?.backgroundColor = UIColor.white
self.view.addSubview(tstview!)
}
override func viewDidLoad() {
super.viewDidLoad()
}
//removing UIView by touching elsewhere
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
tstview?.removeFromSuperview()
// tstview = nil
}
}
deinit is called when no one is referencing the object. If you don't set tstview to nil, your MyViewController is still referencing it, thus deinit won't be called. When you call addView, the statement tstview = test finally removes the last reference to the old view, thus triggering the deinitializer.
You can read more about the concept of deinitialization in the Swift documentation.
If you want to be notified as soon as the view is detached, override willMove(toSuperview:) instead.
class TestView: UIView {
...
override func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
print("removed from parent")
}
}
}

Adding button to GameScene.swift programatically and transitioning scenes when pressed

I have been working forever trying to implement a way to add a button and when pressed the scene transitions to my second view. I have read other posts but have had ZERO luck for something in Swift 3. I'm really confused and have tried but failed many times. Hope you can help! Thanks!
Swift 3 in SpriteKit.
What do you mean transition to a new view?. When making SpriteKit games we tend to transition between SKScenes and not views. So do not try to create different views or viewControllers for each scene, just transition between SKScenes directly.
In regards to buttons, there is plenty tutorials available. You basically create a SKSpriteNode as a button and look for it in touchesBegan and do something when its pressed.
This is a simple example here
https://nathandemick.com/2014/09/buttons-sprite-kit-using-swift/
Essential you can create a button subclass similar to this.
class Button: SKNode {
let defaultButton: SKSpriteNode
let activeButton: SKSpriteNode
var action: () -> ()
init(defaultButtonImage: String, activeButtonImage: String, buttonAction: #escaping () -> ()) {
defaultButton = SKSpriteNode(imageNamed: defaultButtonImage)
activeButton = SKSpriteNode(imageNamed: activeButtonImage)
activeButton.isHidden = true
action = buttonAction
super.init()
isUserInteractionEnabled = true
addChild(defaultButton)
addChild(activeButton)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
activeButton.isHidden = false
defaultButton.isHidden = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
activeButton.isHidden = false
defaultButton.isHidden = true
} else {
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
action()
}
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
and than in your relevant SKScene add your buttons
class StartScene: SKScene {
override func didMove(to view: SKView) {
let playButton = Button(defaultButtonImage: "button", activeButtonImage: "button_active", buttonAction: loadGameScene)
playButton.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(playButton)
}
func loadGameScene() {
let scene = GameScene(...)
let transition = SKTransition....
scene.scaleMode = .aspectFill
view?.presentScene(scene, transition: transition)
}
}
You can also check out Apples sample game DemoBots for another button class example using protocols.
Hope this helps