i'm trying to create a vary simple game on Swift based on Balloons.playground (that Apple showed on WWDC). There is code that Apple provides:
func fireCannon(cannon: SKNode) {
let balloon = createRandomBalloon()
displayBalloon(balloon, cannon)
fireBalloon(balloon, cannon)
}
let leftBalloonCannon = scene.childNodeWithName("//left_cannon")!
let left = SKAction.runBlock { fireCannon(leftBalloonCannon) }
I do the same (i suppose):
func displayFruit(xPos: CGFloat) -> Void {
let fruit = SKSpriteNode(imageNamed: "Banana")
fruit.size = CGSize(width: 100, height: 100)
fruit.position = CGPoint(x:xPos, y: 800)
fruit.physicsBody = SKPhysicsBody(texture: fruit.texture, size: fruit.size)
fruit.physicsBody?.affectedByGravity = true
self.addChild(fruit)
}
let start = SKAction.runBlock { displayFruit(100) }
This code above i put at override func didMoveToView(view: SKView)
I get an error: Cannot reference a local function with capture from another function
I know there was very the same questions, but solutions there don't seemed helpful for me.
What would be the right way to do this?
Thank you!
This is a local function:
override func didMoveToView(view: SKView) {
func displayFruit() {
// ...
}
}
This is not a local function:
override func didMoveToView(view: SKView) {
// ...
}
func displayFruit() {
// ...
}
Make it look like the second one.
Related
I create UIScrollView to be integrated inside SwiftUI view. It contains UIHostingController to host SwiftUI view. When I update UIHostingController, UIScrollView does not change its constraints. I can scroll neither to top nor to bottom. When I try to call viewDidLoad() inside updateUIViewController(_:context:), it works like I expect. Here is my sample code,
struct ContentView: View {
#State private var max = 100
var body: some View {
VStack {
Button("Add") { self.max += 2 }
ScrollableView {
ForEach(0..<self.max, id: \.self) { index in
Text("Hello \(index)")
.frame(width: UIScreen.main.bounds.width, height: 100)
.background(Color(red: Double.random(in: 0...255) / 255, green: Double.random(in: 0...255) / 255, blue: Double.random(in: 0...255) / 255))
}
}
}
}
}
class ScrollViewController<Content: View>: UIViewController, UIScrollViewDelegate {
var hostingController: UIHostingController<Content>! = nil
init(rootView: Content) {
self.hostingController = UIHostingController<Content>(rootView: rootView)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var scrollView: UIScrollView = UIScrollView()
override func viewDidLoad() {
self.view = UIView()
self.addChild(hostingController)
view.addSubview(scrollView)
scrollView.addSubview(hostingController.view)
scrollView.delegate = self
scrollView.scrollsToTop = true
scrollView.isScrollEnabled = true
makeConstraints()
hostingController.didMove(toParent: self)
}
func makeConstraints() {
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
scrollView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
hostingController.view.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
hostingController.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
hostingController.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
}
}
struct ScrollableView<Content: View>: UIViewControllerRepresentable {
var content: () -> Content
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
func makeUIViewController(context: Context) -> ScrollViewController<Content> {
let vc = ScrollViewController(rootView: self.content())
return vc
}
func updateUIViewController(_ viewController: ScrollViewController<Content>, context: Context) {
viewController.hostingController.rootView = self.content()
viewController.viewDidLoad()
}
}
I don't think it is a good way to do. I want to know if there is the best way to update controller. If anyone knows the best solution, share me please. Thanks.
You are correct, we should never call our own viewDidLoad.
Let’s diagnose the issue, using the view debugger. So, for example, here it is (setting max to 8 to keep it manageable):
Note the height of the hosting controller’s view is 800 (because we have 8 subviews, 100 pt each). So far, so good.
Now tap the “add” button and repeat:
We can see that the problem isn’t the scroll view, but rather the hosting view controller’s view. Even though there are now 10 items, it still thinks the hosting view controller’s view’s height is 800.
So, we can call setNeedsUpdateConstraints and that fixes the problem:
func updateUIViewController(_ viewController: ScrollViewController<Content>, context: Context) {
viewController.hostingController.rootView = content()
viewController.hostingController.view.setNeedsUpdateConstraints()
}
Thus:
struct ContentView: View {
#State private var max = 8
var body: some View {
GeometryReader { geometry in // don't reference `UIScreen.main.bounds` as that doesn’t work in split screen multitasking
VStack {
Button("Add") { self.max += 2 }
ScrollableView {
ForEach(0..<self.max, id: \.self) { index in
Text("Hello \(index)")
.frame(width: geometry.size.width, height: 100)
.background(Color(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1)))
}
}
}
}
}
}
class ScrollViewController<Content: View>: UIViewController {
var hostingController: UIHostingController<Content>! = nil
init(rootView: Content) {
self.hostingController = UIHostingController<Content>(rootView: rootView)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var scrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad() // you need to call `super`
// self.view = UIView() // don't set `self.view`
addChild(hostingController)
view.addSubview(scrollView)
scrollView.addSubview(hostingController.view)
// scrollView.delegate = self // you're not currently using this delegate protocol, so we probably shouldn't set the delegate
// scrollView.scrollsToTop = true // these are the default values
// scrollView.isScrollEnabled = true
makeConstraints()
hostingController.didMove(toParent: self)
}
func makeConstraints() {
NSLayoutConstraint.activate([
// constraints for scroll view w/in main view
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// define contentSize of scroll view relative to hosting controller's view
hostingController.view.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor)
])
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
}
}
struct ScrollableView<Content: View>: UIViewControllerRepresentable {
var content: () -> Content
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
func makeUIViewController(context: Context) -> ScrollViewController<Content> {
ScrollViewController(rootView: content())
}
func updateUIViewController(_ viewController: ScrollViewController<Content>, context: Context) {
viewController.hostingController.rootView = content()
viewController.hostingController.view.setNeedsUpdateConstraints()
}
}
In App Delegate:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask(rawValue: UIInterfaceOrientationMask.landscape.rawValue)
}
In my View Controller(MainViewController) I have added
override func viewDidLoad() {
super.viewDidLoad()
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
supportedInterfaceOrientations()
preferredInterfaceOrientationForPresentation()
// Do any additional setup after loading the view.
}
private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask(rawValue: UIInterfaceOrientationMask.portrait.rawValue)
}
private func shouldAutorotate() -> Bool {
return true
}
private func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
// Only allow Portrait
return UIInterfaceOrientation.portrait
}
This is the only controller in the application that I want to work in portrait mode. except this everything in Landscape mode.
But I've tried numerous things still unable to understand why is it not working.
Thanks in advance. Sorry for being noob in swift.
write this code in appdelegate
var shouldRotate = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if shouldRotate {
return .landscape
}
else {
return .portrait
}
}
set this code to your view controller in viewDidload()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.shouldRotate = true // or false to disable rotation
//you can manage only changing true or false
hope its helps you
In my tvOS app I created a settings bundle, but I don't know how to get the values in TVML. I know how to do it in Obj-c or Swift.
var standardUserDefaults = NSUserDefaults.standardUserDefaults()
var us: AnyObject? = standardUserDefaults.objectForKey("your_preference")
if us==nil {
self.registerDefaultsFromSettingsBundle();
}
Any ideas about TVML way? Any kind of help is highly appreciated.
I am not aware of a direct TVJS access method... but you could easily set up a Swift/Obj-C-"proxy". Somewhat along those lines:
AppDelegate.swift
func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext) {
let jsInterface: cJsInterface = cJsInterface();
jsContext.setObject(jsInterface, forKeyedSubscript: "swiftInterface")
}
JsInterface.swift
#objc protocol jsInterfaceProtocol : JSExport {
func getSetting(setting: String) -> String
}
class cJsInterface: NSObject, jsInterfaceProtocol {
func getSetting(setting: String) -> String {
return "<yourSetting>"
}
}
on the JS side...
swiftInterface.getSetting(...)
I was just curious as to how I would approach this. If I had a function, and I wanted something to happen when it was fully executed, how would I add this into the function? Thanks
Say you have a download function to download a file from network, and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
// How to use it.
downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
})
I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.
My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.
To create a function with a completion handler
func yourFunctionName(finished: () -> Void) {
print("Doing something!")
finished()
}
to use the function
override func viewDidLoad() {
yourFunctionName {
//do something here after running your function
print("Tada!!!!")
}
}
Your output will be
Doing something
Tada!!!
Simple Example:
func method(arg: Bool, completion: (Bool) -> ()) {
print("First line of code executed")
// do stuff here to determine what you want to "send back".
// we are just sending the Boolean value that was sent in "back"
completion(arg)
}
How to use it:
method(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
We can use Closures for this purpose. Try the following
func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
//some code here
completionClosure(indexes: list)
}
At some point we can call this function as given below.
healthIndexManager.loadHealthCareList { (indexes) -> () in
print(indexes)
}
Please refer the following link for more information regarding Closures.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
In addition to above : Trailing closure can be used .
downloadFileFromURL(NSURL(string: "url_str")!) { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
}
In case you need result values in your completion handler, it's a good idea to include labels proceeded with underscores, like this...
func getAccountID(account: String, completionHandler: (_ id: String?, _ error: Error?) -> ()) {
// Do something and return values in the completion handler
completionHandler("123", nil)
}
...because when you type this function, Xcode will automatically fill in the result value labels, like this:
getAccountID(account: inputField.stringValue) { id, error in
}
I'm a little confused about custom made completion handlers. In your example:
Say you have a download function to download a file from network,and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
Your // download code will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true and completion Handler(success: flag) without waiting for your download code to be finished?
//MARK: - Define
typealias Completion = (_ success:Bool) -> Void
//MARK: - Create
func Call(url: NSURL, Completion: Completion) {
Completion(true)
}
//MARK: - Use
Call(url: NSURL(string: "http://")!, Completion: { (success) -> Void in
if success {
//TRUE
} else {
//FALSE
}
})
Is there any difference in swift between function declaration:
func function(a: String) {
print(a);
}
function("test");
and closure assignment:
let closure = {
(a: String) in
print(a);
}
closure("test");
Is there any difference between those?
Named or anonymous
func function(a: String) {
print("\(a), name: \(__FUNCTION__)");
}
let closure = { (a: String) in
print("\(a), name: \(__FUNCTION__)");
}
Capture List
supported in closures only:
let obj = FooClass()
let closure = { [weak obj] in ... }
Curried function
supported in functions only:
func curriedFunc(x:Int)(y:Int) { ... }
let curried = curriedFunc(1)
curried(y:2)
Similar, but not exact the same with using closure:
let closure = { (x:Int) in { (y:Int) in ... }}
Generics
supported in functions only:
func function<T>(x:T) { ... }
Referenceability from its own initial declaration
supported in global functions only:
func recursive(var x:Int) -> Int {
...
return condition ? x : recursive(x)
}
You can do this using closure also:
var recursive:((Int) -> Int)!
recursive = { (var x) in
...
return condition ? x : recursive(x)
}
But this is not recommended because this causes strong reference cycles.
Overload
supported in functions only:
func function(a: String) { print("String: \(a)") }
func function(a: Float) { print("Float: \(a)") }
n.b. You can reference them as a closure like this:
let f:(Float) -> Void = function
Another difference: recursivity inside another function
Nested functions cannot be recursive:
func foo() {
func bar() { bar() } // does not compile
}
but closures inside other functions can be recursive:
func foo() {
var bar: (() -> ())!
bar = { bar() }
}