How to access var of an extension in another class? - swift

I´m working with Sprite Kit. I want to change the button picture of the main class with the settings class. How can I make the variable in the extension (from the setting class) available for the main class?
Here is the extension:
extension ChangingDots {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
for touch in touches{
let locationUser = touch.location(in: self)
if atPoint(locationUser) == DCButton {
var blackdot = SKSpriteNode(imageNamed: "AppIcon") //<--var I want to use
}
}
}
}
Here is the use in the main class:
blackdot.setScale(0.65)
blackdot.position = CGPoint(x: CGFloat(randomX), y: CGFloat(randomY))
blackdot.zPosition = 1
self.addChild(blackdot)
Does anyone have a better idea of changing button pictures of one class from another?

If you want to use a variable in the main class, it needs to be created in the main class. Extensions are designed to extend functionality, this means functions and computed properties.
To find out more, see this documentation:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

Just to add on here, there are ways to "workaround" adding stored properties in an extension. Here is an article that describes how to do it: https://medium.com/#ttikitu/swift-extensions-can-add-stored-properties-92db66bce6cd
However, if it were me, I would add the property to your main class. Extensions are meant to extend behavior of a class. It doesn't seem to be the right design approach to make a main class DEPENDENT on your extension.
If you want to make it private, you can use fileprivate so your extension can access it but maintain it's "private" access. For example:
fileprivate var value: Object? = nil

Sorry but you make me realize that you can't add stored properties in extensions. You can only add computed properties. You can add your blackdot var as a computed property or declare it in your main class instead of your extension. If you want to try the computed way, use this :
extension ChangingDots {
var blackdot:Type? { // Replace Type with SKSpriteNode type returned
return SKSpriteNode(imageNamed: "AppIcon")
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
for touch in touches {
let locationUser = touch.location(in: self)
if atPoint(locationUser) == DCButton {
blackdot = SKSpriteNode(imageNamed: "AppIcon") //<--var I want to use
}
}
}
}
This way your blackdot var is only gettable and NOT settable. If you want to add the possibility to set it you need to add a setter like this :
var blackdot:Type? { // Replace Type with SKSpriteNode type returned
get {
return SKSpriteNode(imageNamed: "AppIcon")
}
set(newImage) {
...
}
}

Related

Reality Composer - ar hittest not working?

Alright, Im weeding thru the provided RealityComposer game at https://developer.apple.com/videos/play/wwdc2019/609/ and am trying to figure out how to have an entity move where the user taps.
I can reference my objects in my .rc scene like this:
struct ARViewContainer: UIViewRepresentable {
let arView = ARView(frame: .zero)
func makeUIView(context: Context) -> ARView {
// arView = ARView(frame: .zero)
// Load the "Box" scene from the "Experience" Reality File
let boxAnchor = try! Experience.loadBox()
//*Notifications
setupNotifications(anchor: boxAnchor)
//*Access vars
if boxAnchor.box1 != nil {
//print(box1.position.x)
/// Set local position
boxAnchor.box1!.position = [1.0, 0.0, 0.5]
/// Set world position
//boxAnchor.box1.setPosition([0.5, 0.2, 1.5], relativeTo: nil)
}
I know this involves some form arhitest, however with the following I get the error:
UIView has no member last?
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//1. Get The Current Touch Location
guard let currentTouchLocation = touches.first?.location(in: self.arView),
//2. Get The Tapped Node From An SCNHitTest
let hitTestResultNode = self.arView.hitTest(currentTouchLocation, with: nil).last?.node else { return } //error here
//3. Loop Through The ChildNodes
for node in hitTestResultNode.childNodes{
//4. If The Node Has A Name Then Print It Out
if let validName = node.name{
print("Node\(validName) Is A Child Node Of \(hitTestResultNode)")
}
}
}
Im pretty lost as to whether Im going about this at all correctly. Im referencing Detect touch on SCNNode in ARKit but this does not deal with RealityComposer.
How can I do this?
The simplest way to get an Entity to move via touch is to use the built in gestures provides by Apple; which you can read more about here: Apple Documentation
To enable your gesture of choice (in this case translation), first ensure that in RealityComposer that you set the partcipates value to true on every Entity you wish to interact with.
This then adds a Has Collision component to the Entitywhich is simply:
A component that gives an entity the ability to collide with other entities that also have collision components.
Using this you can install built in gestures to do the heavy lifting for you.
Assuming we have the default RealityKit example setup in Xcode, and we have selected participates for the box, its a simple as this to enable the user to pan it using the touch location:
class ViewController: UIViewController {
#IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
//1. Load The Box Anchor
let boxAnchor = try! Experience.loadBox()
//2. Check The SteelBox Has A Collision Component & Add The Desired Gesture
if let hasCollision = boxAnchor.steelBox as? HasCollision {
arView.installGestures(.translation, for: hasCollision)
}
//Add The Box To The Scene Hierachy
arView.scene.anchors.append(boxAnchor)
}
}
Alternatively if you wanted to do some heavy lifting (who doesn't!) then you could do something like this by creating a global variable which will reference the Entity that you have selected (which in this case is called Steel Box):
//Variable To Store Our Currently Selected Entity
var currentEntity: Entity?
Then using touchesBegan and touchesMoved you can something like this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Get The Current Touch Location In The ARView
Perform A HitTest For The Nearest Entity
Checks That The Tapped Entity Is The Steel Box
Set It As The Current Entity
*/
guard let touchLocation = touches.first?.location(in: arView),
let tappedEntity = arView.hitTest(touchLocation, query: .nearest, mask: .default).first?.entity,
tappedEntity.name == "Steel Box" else {
return
}
currentEntity = tappedEntity
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Get The Current Touch Location In The ARView
Perform A HitTest For An Existing Plane
Move The Current Entity To The New Transfortm
Set It As The Current Entity
*/
guard let touchLocation = touches.first?.location(in: arView),
let currentEntity = currentEntity else {
return
}
if let transform = arView.hitTest(touchLocation, types: .existingPlaneUsingExtent).first?.worldTransform {
currentEntity.move(to: transform, relativeTo: nil, duration: 0.1)
}
}
Hope it helps point the in the right direction.

IOS Swift Protocol is not working or hitting breakpoint

I created a question a few days ago and was provided with protocol on how to solve an issue of passing data back and forth . I have also looked at some tutorials and have created a protocol but it is not working or even hitting the breakpoint from what I can see it should be working. I have created a protocol for my AVPlayer so that on tap it could get a new video but like i said it's not even hitting the breakpoint this is my code...
protocol CustomAVPLayerProtocol: class {
func reloadTabled(at index: Int)
}
class CustomAVPLayerC: AVPlayerViewController {
var delagate: CustomAVPLayerProtocol?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.delagate?.reloadTabled(at: 1)
for touch in touches {
self.delagate?.reloadTabled(at: 1)
print("Tapped")
// When I tap the AVPlayer this print statement shows
// So I know it is coming here
}
}
}
Now This is my second class/controller
class BookViewC: UIViewController, CustomAVPLayerProtocol {
override func viewDidLoad() {
super.viewDidLoad()
PlayVideo(250, "url")
}
func reloadTabled(at index: Int) {
print("This protocol method does not execute or hit breakpoint")
self.PlayVideo(250, "url")
}
func PlayVideo(MediaHeight: Float, MediaURL: String) {
let movieURL = URL(string: MediaURL)
videoCapHeight.constant = CGFloat(MediaHeight)
streamsModel.playerView = AVPlayer(url: movieURL!)
streamsModel.MyAVPlayer.player = streamsModel.playerView
streamsModel.MyAVPlayer.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
streamsModel.MyAVPlayer.showsPlaybackControls = false
streamsModel.MyAVPlayer.view.frame = VideoView.bounds
VideoView.addSubview(streamsModel.MyAVPlayer.view)
self.addChildViewController(streamsModel.MyAVPlayer)
streamsModel.playerView?.isMuted = false
streamsModel.MyAVPlayer.player?.play()
}
}
As I stated before it is not even hitting the breakpoint on BookViewC.reloadTabled as suggestions would be great
As per your code these are some minor mistakes which you can correct to make it work.
1. `weak var delagate: CustomAVPLayerProtocol?`
*Make a weak delegate to save it from retaining a strong reference cycle and memory leaks.*
2. Code Snippet:
func PlayVideo {
let customPlayer = CustomAVPLayerC()
customPlayer.delegate = self
}
in Your Second ViewController, You need to assign your delegate to an object / view controller to make ie respond to
NOTE: In case you require, you can make a super class that conforms the your protocol class, so that your every view controller conforms it automatically, you just need to assign an delegate to class on which you want to use it.
You have the foundation set up correctly but remember that classes are (mostly) just blueprints for instances. These classes are useless until you create instances of them because it’s the instances that will do the work.
Therefore, simply pass one instance as the delegate of the other, which you can do here because you've correctly set up the protocol.
protocol CustomAVPLayerProtocol: AnyObject {
func reloadTabled(at index: Int)
}
class CustomAVPLayerC: AVPlayerViewController {
weak var delagate: CustomAVPLayerProtocol?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.delagate?.reloadTabled(at: 1)
for touch in touches {
self.delagate?.reloadTabled(at: 1)
print("Tapped")
}
}
}
class BookViewC: UIViewController, CustomAVPLayerProtocol {
override func viewDidLoad() {
super.viewDidLoad()
PlayVideo(250, "url")
}
func reloadTabled(at index: Int) {
PlayVideo(250, "url")
}
func PlayVideo(_ MediaHeight: Float, _ MediaURL: String) {
//
}
}
let book = BookViewC()
let layer = CustomAVPLayerC()
layer.delagate = book
Where you do this instantiation/delegation is up to you. Also, I know that a lot of people here use class to define protocols that only conform to classes, but Swift's documentation instructs us to use AnyObject.
Protocols are the most common means used by unrelated objects to communicate with each other. As per the above code, the communication did not seem to happen.
Your protocol declaration part seems alright. The problem exists in the secondViewController. I can see that you have not set the delegate to the object that's been created. Ideally, it has to be something like this:
Class BookViewC: UIViewController, CustomAVPLayerProtocol {
override func viewDidLoad() {
super.viewDidLoad()
PlayVideo(250, "url")
}
You need to the set the delegate here:
func PlayVideo {
let customPlayer = CustomAVPLayerC()
customPlayer.delegate = self //This makes the selector to respond
}

Nodes not moving

(Swift 3)
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var object = SKSpriteNode()
override func didMove(to view: SKView) {
object = self.childNode(withName: "dot") as! SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
object.run(SKAction.move(to: location, duration: 0.3))
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
object.run(SKAction.move(to: location, duration: 0.3))
}
}
override func update(_ currentTime: TimeInterval) {
}
}
This code is designed to allow me to drag a "dot" around the scene, however... I just cant! It won't budge! I've looked online, but I can't find anything. I tried pasting this code into a fresh project, and it worked there, but even deleting and replacing my "dot" node doesn't seem to help on my main project.
So... any ideas?
Confused has already said everything you must know about your issue.
I try to add details that help you with the code. First of all, you should use optional binding when you search a node with self.childNode(withName so if this node does not exist your project does not crash.
Then, as explained by Confused, you should add controls before you call your actions to be sure that your action is not already running.
I make an example here below:
import SpriteKit
class GameScene: SKScene {
var object = SKSpriteNode.init(color: .red, size: CGSize(width:100,height:100))
override func didMove(to view: SKView) {
if let sprite = self.childNode(withName: "//dot") as? SKSpriteNode {
object = sprite
} else { //dot not exist so I draw a red square..
addChild(object)
}
object.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
}
func makeMoves(_ destination: CGPoint) {
if object.action(forKey: "objectMove") == nil {
object.run(SKAction.move(to: destination, duration: 0.3),withKey:"objectMove")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
makeMoves(location)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
makeMoves(location)
}
}
}
Output:
The fact it works in a new, barebones project, and not in your fuller project indicates the problem is in the fuller project. Without a glimpse at that, it's pretty hard to tell what's actually going wrong.
Peculiar, to me, is the use of the SKAction to do the move in touchesMoved(). If you think about this in terms of how SKActions works, you're continually adding new move actions, at whatever rate the touchscreen is picking up changes in position. This is (almost always) much faster than 0.3 seconds. More like 0.016 seconds. So this should be causing all manner of problems, in its own right.
Further, you need something in the GameScene's touchesMoved() to ascertain what's being touched, and then, based on touching the dot, move it, specifically. This, I assume, is your "object".
A simpler way of doing this might be to use touchesMoved in a subclass of SKSpriteNode that represents and creates your dot instance.

Where do I call the Subclass? (reselectable UISegmentControl Swift 3)

I have a subclass for a UISegmentedControl which is called SegControl in a Cocoa Touch Class.
class SegControl: UISegmentedControl {
override var = "test"
}
And now I have a UISegmentControl in my ViewController what do I have to do that this conforms to my custom class?
EDIT:
Full code for a Reselectable UISegmentControl for Swift 3
class ReselectableSegmentedControl: UISegmentedControl {
#IBInspectable var allowReselection: Bool = true
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let previousSelectedSegmentIndex = self.selectedSegmentIndex
super.touchesEnded(touches, with: event)
if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
if let touch = touches.first {
let touchLocation = touch.location(in: self)
if bounds.contains(touchLocation) {
self.sendActions(for: .valueChanged)
}
}
}
}
}
UISegmentControl:
var savedSegment: Int = -1
#IBAction func segmentChanged(_ sender: ReselectableSegmentedControl) {
if (sender.selectedSegmentIndex == savedSegment) {
sender.selectedSegmentIndex = UISegmentedControlNoSegment
savedSegment = UISegmentedControlNoSegment
}
else {
savedSegment = sender.selectedSegmentIndex
}
Your question isn't entirely clear but to start you need to replace any references to UISegmentedControl with SegControl. This includes updating any references in code as well as changing the class name of the object in any storyboard or xib.
You are also going to need to add the proper init methods to your subclass so you can create instances of it.
And of course you need to added whatever additional code that makes having this subclass useful.
add a default UISegmentControl in your layout builder
then click on it and in the side menu under identity inspector -> class
write your class name SegControl

Swift / SpriteKit Button Drag Off Cancel Not Working?

Hello I need your help I have been looking a while now to find the Answer to this.
I also have simplified the code to get rid of allot of the information/junk you don't need to know.
I have a main menu scene in for a IOS game using SpriteKit And Swift. There Is a main menu play button. What I want is When the button is pressed the button get bigger by a little. When the my finger is release the button gets smaller. This works fine using override func touchesBegan / touchesEnded. my problem is when my finger gets dragged off the button like to cancel. The button does not return to the original size. I am pretty sure I need to use
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {}
But upon many attempts I am not getting the the desired result of returning the button to original size when my finger is dragged off the button. Thanks for any help.
import Foundation
import SpriteKit
import UIKit
class StartScene: SKScene {
var playButton: SKNode! = nill
override func didMoveToView(view: SKView) {
// Create PlayButton image
playButton = SKSpriteNode(imageNamed: "playButtonStatic")
// location of Button
playButton.position = CGPoint(x:CGRectGetMidX(self.frame), y:520);
self.addChild(playButton)
playButton.setScale(0.5)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if playButton.containsPoint(location) {
playButton.setScale(0.6)}}}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if playButton.containsPoint(location) {
playButton.setScale(0.5)
}}}
// Problem Area
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
for touch: AnyObject in touches! {
let location = touch.locationInNode(self)
if playButton.containsPoint(location) {
playButton.setScale(0.5)
}}}
}
Thanks for any response
Found the solution use a Else statement in TouchesEnded
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if playButton.containsPoint(location) {
playButton.setScale(0.5)
}
else
{
playButton.setScale(0.5)
}}
You say you found a solution but here's an easier solution: use a custom class I created designed specifically for buttons for SpriteKit. Link to the GitHub that has the class file. With this class, you don't have to worry about it at all, and it removes unnecessary code from your touches functions. JKButtonNodes have 3 states: normal, highlighted, and disabled. You also don't have to worry about setting it to nil if you have removed it from the parent.
To declare a variable, do this. Ignore the playButtonAction error for now.
var playButton = JKButtonNode(background: SKTexture(imageNamed: "playButtonStatic"), action: playButtonAction)
The action is the function to call when the button is pressed and let go. Create a function like this anywhere in your class.
func playButtonAction(button: JKButtonNode) {
//Whatever the button does when pressed goes here
}
Then you can set its properties in didMoveToView.
playButton.position = CGPoint(x:CGRectGetMidX(self.frame), y:520)
//These are the 3 images you want to be used when pressed/disabled
//You can create a bigger image for when pressed as you want.
playButton.setBackgroundsForState(normal: "playButtonStatic", highlighted: "playButtonHighlighted", disabled: "")
addChild(playButton)
And that's it! The JKButtonNode class itself already cancels touches if the user moves their finger off, it also doesn't call the function unless the user has successfully pressed the button and released their finger on it. You can also do other things like disable it from playing sounds, etc.
A good pro of using JKButtonNode is that you don't have to have code all over the place anymore since it doesn't require ANY code in the touches functions.