iOS Development – Tech TeTo https://techteto.com Fri, 26 Nov 2021 19:38:26 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.2 https://i0.wp.com/techteto.com/wp-content/uploads/2021/11/cropped-TECH-TETO-Logo-1.png?fit=32%2C32&ssl=1 iOS Development – Tech TeTo https://techteto.com 32 32 200223637 The way to construct higher command line apps and instruments utilizing Swift? https://techteto.com/the-way-to-construct-higher-command-line-apps-and-instruments-utilizing-swift/ https://techteto.com/the-way-to-construct-higher-command-line-apps-and-instruments-utilizing-swift/#respond Fri, 26 Nov 2021 19:38:26 +0000 https://techteto.com/how-to-build-better-command-line-apps-and-tools-using-swift/ 2021/08/05 The following tips will allow you to to create superb CLI instruments, utility apps, server aspect tasks or terminal scripts utilizing the Swift language. Swift Operating Swift recordsdata as scripts It’s attainable to run a Swift file straight from the command line if you happen to add a hashbang to the […]

The post The way to construct higher command line apps and instruments utilizing Swift? appeared first on Tech TeTo.

]]>

The following tips will allow you to to create superb CLI instruments, utility apps, server aspect tasks or terminal scripts utilizing the Swift language.

Swift

Operating Swift recordsdata as scripts


It’s attainable to run a Swift file straight from the command line if you happen to add a hashbang to the start of the file. This fashion you do not have to manually compile the code utilizing the swiftc command. You may merely give the file the executable permission flag and the system will name the Swift REPL below the hood, so our app could be evaluated mechanically. šŸ”Ø


#!/usr/bin/env swift

print("Hiya, world!")



For instance this major.swift file above could be marked as an executable file, and we will merely name it by way of the ./major.swift command afterward (you simply have to make use of chmod just one time).


chmod +x major.swift 
./major.swift  


The great thing about this technique is which you could quickly take a look at your Swift command line snippets. You may even place the completed Swift scripts below the /usr/native/bin/ listing with out the swift file extension to make them out there “globally” to your working system consumer. šŸ’Ŗ




Utilizing command line arguments in Swift

The CommandLine enum makes it very simple to fetch the arguments handed to our Swift utility or script. You may entry each argument utilizing the arguments variable as an array of Strings, however it’s also attainable to get the uncooked knowledge utilizing the argc and unsafeArgv properties.


#!/usr/bin/env swift


let script = CommandLine.arguments[0]
print("Script:", script)


let inputArgs = CommandLine.arguments.dropFirst()
print("Variety of arguments:", inputArgs.rely)

print("Arguments:")
for arg in inputArgs {
    print("-", arg)
}


It is best to word that the primary argument is at all times the trail of the present script, so in case you are solely on the lookout for the enter arguments you need to use the dropFirst() technique to return a subset of the enter strings. Often every argument is separated by an area character.


./major.swift whats up world




In Xcode you’ll be able to add customized arguments below the Edit Scheme… menu merchandise whenever you click on on the present scheme, search for the Arguments tab and use the Arguments Handed On Launch part.



Course of information and setting in Swift

Identical to we will entry command line arguments, it’s attainable to look at the present course of together with some {hardware} info and setting variables.


#!/usr/bin/env swift
import Basis

let information = ProcessInfo.processInfo

print("Course of information")
print("Course of identifier:", information.processIdentifier)
print("System uptime:", information.systemUptime)
print("Globally distinctive course of id string:", information.globallyUniqueString)
print("Course of title:", information.processName)

print("Software program information")
print("Host title:", information.hostName)
print("OS main model:", information.operatingSystemVersion.majorVersion)
print("OS model string", information.operatingSystemVersionString)

print("{Hardware} information")
print("Lively processor rely:", information.activeProcessorCount)
print("Bodily reminiscence (bytes)", information.physicalMemory)


print("Arguments")
print(ProcessInfo.processInfo.arguments)

print("Surroundings")

print(information.setting)


The setting variables property is a Dictionary the place each the keys and the values can be found as strings, so that you might need to parse them in case you are on the lookout for completely different worth sorts. You may arrange setting customized variables in Xcode identical to arguments, or you’ll be able to go them by way of the command line earlier than you execute the Swift script utilizing the export command.





Customary enter and output in Swift

You should use the print operate to put in writing textual content to the usual output, however you need to word that the print operate has a variadic gadgets definition, so you’ll be able to go round a number of arguments and a customized separator & terminator parameter to show extra superior outputs.


There may be additionally a typical error stream, which is a part of the normal streams after all, however what’s attention-grabbing about it’s which you could additionally write to this channel by means of the FileHandle.standardError property there may be fairly a chic resolution on a Stack Overflow thread initially created by Rob Napier, I will embrace that one right here as nicely. šŸ™


One other nice function of the print operate is the to parameter, which might settle for a customized TextOutputStream so you’ll be able to wrap the stderr stream in a customized object or you can too create customized output handlers and separate your print statements e.g. by context if you happen to want.


#!/usr/bin/env swift
import Basis


print("This", "is", "enjoyable", separator: "-", terminator: "!")


"This goes to the usual error output"
    .knowledge(utilizing: .utf8)
    .map(FileHandle.standardError.write)


ultimate class StandardErrorOutputStream: TextOutputStream {
    func write(_ string: String) {
        FileHandle.standardError.write(Information(string.utf8))
    }
}

var outputStream = StandardErrorOutputStream()
print("That is additionally an error", to: &outputStream)



func clear() {
    print("u{1B}[2J")
    print("u{1B}[(1);(0)H", terminator: "")
}

print("foooooooooooooooooooooo")
clear()
print("Hello, world!")



print("u{1b}[31;1mu{1b}[40;1m("Hello, world!")u{1b}[m")
print("u{1b}[32;1m("Hello, world!")u{1b}[m")


print("Please enter your input:")
guard let input = readLine(strippingNewline: true) else {
    fatalError("Missing input")
}
print(input)


The second half of the snippet is full of ANSI escape codes which I like quite a lot, because it can make our terminal output quite beautiful. The only problem is that they don’t work in Xcode at all (come-on Apple, please support this…). You can clear the console or change the background / foreground color of the output by using these codes.


There are quite a lot of libraries on GitHub that you can use to print colorful output, for example ColorizeSwift, ANSITerminal, ANSIEscapeCode and many more cool ones.


The very last thing that I’d like to show you is the readLine function, which you can use to read a line from the standard input. This comes handy if you need to get user input from the command line.




Use an argument parser library


If you are looking for a type-safe argument parser written in Swift, you should definitely take a look at the Swift Argument Parser library. It is created and maintained by Apple, so it’s kind of an official solution for this particular issue, but IMHO it lacks some advanced features.


This is the main reason why I prefer the Vapor command API built on top of the ConsoleKit library. Both libraries can parse arguments, options and flags, but ConsoleKit is also capable of displaying progress indicators, it features multiple command groups, secure input, auto-completion, multiple log levels and many more.




import Foundation
import ConsoleKit

final class HelloCommand: Command {
        
    struct Signature: CommandSignature {

        @Argument(name: "name", help: "The name to say hello")
        var name: String

        @Option(name: "greeting", short: "g", help: "Greeting used")
        var greeting: String?

        @Flag(name: "capitalize", short: "c", help: "Capitalizes the name")
        var capitalize: Bool
    }

    static var name = "hello"
    let help = "This command will say hello to a given name."

    func run(using context: CommandContext, signature: Signature) throws {
        let greeting = signature.greeting ?? "Hello"
        var name = signature.name
        if signature.capitalize {
            name = name.capitalized
        }
        print("(greeting) (name)!")
        
        
        let bar = context.console.progressBar(title: "Hello")
        bar.start()
        
        bar.succeed()
        
        
        let foo = context.console.ask("What?")
        print(foo)
        
        
        let baz = context.console.ask("Secure what?", isSecure: true)
        print(baz)
        
        
        let c = context.console.choose("Make a choice", from: ["foo", "bar", "baz"])
        print(c)

        
    }
}


import Basis
import ConsoleKit

let console: Console = Terminal()
var enter = CommandInput(arguments: CommandLine.arguments)
var context = CommandContext(console: console, enter: enter)

var instructions = Instructions(enableAutocomplete: true)
instructions.use(HelloCommand(), as: HelloCommand.title, isDefault: false)

do {
    let group = instructions.group(assist: "Utilizing ConsoleKit with out Vapor.")
    strive console.run(group, enter: enter)
}
catch {
    console.error("(error)")
    exit(1)
}


You should use each resolution by means of the Swift Package deal Supervisor, the setup course of is sort of simple, you may discover extra tutorials concerning the Swift Argument Parser and I believe that it’s more durable to seek out correct docs for ConsoleKit, so yeah… anyway, they’re nice libraries you will not remorse utilizing them. šŸ˜‰




Reap the benefits of the Swift Package deal Supervisor

The Swift Package deal Supervisor is likely one of the neatest thing concerning the Swift programming language. I actually adore it and I take advantage of it nearly day-after-day. The truth that the package deal manifest file is outlined utilizing Swift itself makes it simple to make use of & perceive.



import PackageDescription

let package deal = Package deal(
    title: "myProject",
    platforms: [
        .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/console-kit", from: "4.1.0"),
    ],
    targets: [
        .executableTarget(name: "myProject",dependencies: [
            .product(name: "ConsoleKit", package: "console-kit"),
        ]),
        .testTarget(title: "myProjectTests", dependencies: ["myProject"]),
    ]
)


The package deal supervisor developed rather a lot through the previous few months, if you happen to check out the Swift Evolution dashboard you’ll be able to monitor these adjustments, the latest replace was the introduction of customized, user-defined Package deal Collections, however in case you are on the lookout for packages you’ll be able to at all times check out the Swift Package deal Index web site. šŸ‘




The post The way to construct higher command line apps and instruments utilizing Swift? appeared first on Tech TeTo.

]]>
https://techteto.com/the-way-to-construct-higher-command-line-apps-and-instruments-utilizing-swift/feed/ 0 2831
ios – UITableView creating an iPhone settings display screen with Swift https://techteto.com/ios-uitableview-creating-an-iphone-settings-display-screen-with-swift/ https://techteto.com/ios-uitableview-creating-an-iphone-settings-display-screen-with-swift/#respond Fri, 26 Nov 2021 18:37:19 +0000 https://techteto.com/ios-uitableview-creating-an-iphone-settings-screen-with-swift/ I’m attempting to create UITableview with cells, similar to the iPhone settings screenshot. It’s a part of my homework so i’ve to do all of it in UITableview. that is what I did with my code, however every part is purple and full with errors. I attempted to do it following the samples from classes […]

The post ios – UITableView creating an iPhone settings display screen with Swift appeared first on Tech TeTo.

]]>

I’m attempting to create UITableview with cells, similar to the iPhone settings screenshot.

It’s a part of my homework so i’ve to do all of it in UITableview.

that is what I did with my code, however every part is purple and full with errors. I attempted to do it following the samples from classes but it surely kinda appears to be like all incorrect.

Please, assist me perceive how this factor works and what’s incorrect.

import UIKit
struct Strains{
    var picture: [UIImage] = []
    var title: [String] = []
}

class Titles {
    

    static func titles() -> [Lines]{
        return [
            Lines(image: UIImage[ systemName: "airplane"  ,"wifi.square.fill", "bitcoinsign.circle.fill",  "iphone.homebutton.radiowaves.left.and.right", "personalhotpot" ], title: ["Авиарежим" , "Wi-fi", "Bluetooth", "Š”Š¾Ń‚Š¾Š²Š°Ń ŃŠ²ŃŠ·ŃŒ", "Режим моГема"]),
            Strains(picture: UIImage[ systemName: "bell.badge.fill"  ,"speaker.wave.3.fill", "moon.fill",  "iphone.homebutton.radiowaves.left.and.right", "clock.fill" ], title: ["Š£Š²ŠµŠ“Š¾Š¼Š»ŠµŠ½ŠøŃ", "Š—Š²ŃƒŠŗŠø,Ń‚Š°ŠŗŃ‚ŠøŠ»ŃŒŠ½Ń‹Šµ сигналы", "ŠŠµ Š±ŠµŃŠæŠ¾ŠŗŠ¾ŠøŃ‚ŃŒ", "Экранное Š²Ń€ŠµŠ¼Ń"]),
            Strains(picture: UIImage[ systemName: "gear"  ,"switch.2", "display" ] , title: ["ŠžŠ±Ń‰ŠøŠµ", " Control Centre", "Экран Šø ŃŃ€ŠŗŠ¾ŃŃ‚ŃŒ"])
            ]
            }
 
}

class SecondTableViewController: UITableViewController {
    var traces = Titles.titles()
   
    override func viewDidLoad() {
        tremendous.viewDidLoad()
}
}
extension SecondTableViewController: UITableViewDataSource, UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return titles.rely
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
        return titles[section].title.rely
    }
    

    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection part: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SectionCell") as! TableViewCell
        let title = titles[section]
        cell.picture = Strains.picture
        cell.titleLabel.textual content = Strains.title
        return cell
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SecondTableViewCell") as! TableViewCell
        let identify = titles[indexPath.section].title[indexPath.row]
        cell.picture = Strains.picture
        cell.titleLabel.textual content = Strains.title
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
    }
}

Thanks!

The post ios – UITableView creating an iPhone settings display screen with Swift appeared first on Tech TeTo.

]]>
https://techteto.com/ios-uitableview-creating-an-iphone-settings-display-screen-with-swift/feed/ 0 2783
Pasting quoted code completely — Erica Sadun https://techteto.com/pasting-quoted-code-completely-erica-sadun/ https://techteto.com/pasting-quoted-code-completely-erica-sadun/#respond Fri, 26 Nov 2021 17:27:41 +0000 https://techteto.com/pasting-quoted-code-perfectly-erica-sadun/ You may have some code it’s essential incorporate right into a multi-line string. What’s the quickest and greatest strategy to deal with it? Though I see individuals do that on a regular basis, manually including areas to every line isn’t the very best resolution. Right here’s a fast Xcode tip: First, paste your materials into […]

The post Pasting quoted code completely — Erica Sadun appeared first on Tech TeTo.

]]>

You may have some code it’s essential incorporate right into a multi-line string. What’s the quickest and greatest strategy to deal with it? Though I see individuals do that on a regular basis, manually including areas to every line isn’t the very best resolution.

Right here’s a fast Xcode tip:

  • First, paste your materials into scope. Retain the indentation through the use of Edit > Paste and Protect Formatting.
  • Subsequent, when you haven’t positioned them already, add the project and triple-quotes above and under the pasted materials.
  • Choose your materials and use Editor > Construction > Shift-Proper (Command-]) to line up the left fringe of the textual content with the closing triple-quote. This command strikes all chosen materials n areas to the fitting, relying on the way you’ve arrange your tabbing. There’s an identical Shift-Left when you indent somewhat an excessive amount of.

Hope this helps somebody.

The post Pasting quoted code completely — Erica Sadun appeared first on Tech TeTo.

]]>
https://techteto.com/pasting-quoted-code-completely-erica-sadun/feed/ 0 2735
Blissful Black Friday! šŸ› Ā· objc.io https://techteto.com/blissful-black-friday-%f0%9f%9b%8d-%c2%b7-objc-io/ https://techteto.com/blissful-black-friday-%f0%9f%9b%8d-%c2%b7-objc-io/#respond Fri, 26 Nov 2021 16:21:14 +0000 https://techteto.com/happy-black-friday-%f0%9f%9b%8d-%c2%b7-objc-io/ We’re delighted to announce a 30% low cost on all our eBooks and Swift Discuss subscriptions till Monday! This yr, all our bundles are included, with an extra 30% off the common bundle low cost! For instance, The Full Assortment, together with all six books and movies for Superior Swift, App Structure and Pondering in […]

The post Blissful Black Friday! šŸ› Ā· objc.io appeared first on Tech TeTo.

]]>

We’re delighted to announce a 30% low cost on all our eBooks and Swift Discuss subscriptions till Monday!

This yr, all our bundles are included, with an extra 30% off the common bundle low cost! For instance, The Full Assortment, together with all six books and movies for Superior Swift, App Structure and Pondering in SwiftUI, is now solely $209, our largest saving at $90 — if you happen to might stack eBooks, they’d look nice beneath the Christmas tree. šŸŽ„šŸ“š

To use the low cost, use the promo code thanks2020 when shopping for a e book from our web site.

In a uncommon particular, Swift Discuss can also be 30% off. We publish a brand new live-coding episode each week, discussing particular actual world issues and creating options reside, when you watch. Not like conventional tutorials, Swift Discuss is conversational in model, which makes it simpler to observe our thought processes and helps you perceive why we select explicit strategies.

By the way in which: our e book Pondering in SwiftUI might be up to date very quickly (we’re finalizing the modifications) and might be a free replace.

Take pleasure in! 😊

The post Blissful Black Friday! šŸ› Ā· objc.io appeared first on Tech TeTo.

]]>
https://techteto.com/blissful-black-friday-%f0%9f%9b%8d-%c2%b7-objc-io/feed/ 0 2690
Linking to textual content fragments in internet pages – Ole Begemann https://techteto.com/linking-to-textual-content-fragments-in-internet-pages-ole-begemann/ https://techteto.com/linking-to-textual-content-fragments-in-internet-pages-ole-begemann/#respond Fri, 26 Nov 2021 15:20:32 +0000 https://techteto.com/linking-to-text-fragments-in-web-pages-ole-begemann/ Textual content fragments are a manner for internet hyperlinks to specify a phrase or phrase a browser ought to spotlight on the vacation spot web page. Google Chrome added assist for them in model 80 (launched in February 2020). For instance, opening the hyperlink oleb.internet/2020/swift-docker-linux/#:~:textual content=working,container in Chrome ought to spotlight the primary heading of […]

The post Linking to textual content fragments in internet pages – Ole Begemann appeared first on Tech TeTo.

]]>

Textual content fragments are a manner for internet hyperlinks to specify a phrase or phrase a browser ought to spotlight on the vacation spot web page. Google Chrome added assist for them in model 80 (launched in February 2020).

For instance, opening the hyperlink oleb.internet/2020/swift-docker-linux/#:~:textual content=working,container in Chrome ought to spotlight the primary heading of the article:


Screenshot of Chromium highlighting a text fragment
Chromium highlighting the textual content fragment specified within the URL.

The apparent use case is search engines like google: whenever you click on a hyperlink in a search end result, the browser would robotically spotlight your search time period(s) on the vacation spot web page.

I’ve all the time needed this characteristic. I typically discover myself visiting a web page from a search engine, solely to instantly hit Cmd+F and re-type my search question into the browser’s Discover on Web page textual content subject. Evidently, it is a ache on cell gadgets and not using a correct keyboard.

However textual content fragments produce other makes use of past search engines like google:

  1. Linking to a selected sentence or paragraph of an extended doc. I’d use this on a regular basis when linking to API documentation or discussion board posts. ā€œRegularā€ URL fragments solely work for anchors the writer of the vacation spot web page created prematurely, and readers normally can’t see what anchor tags can be found on a web page.
  2. Sharing a particular portion of a web page. Browsers might facilitate this by providing to incorporate a textual content fragment within the URL when sharing a hyperlink to a textual content choice.

Right here’s the pattern URL from above as soon as extra:


https://oleb.internet/2020/swift-docker-linux/#:~:textual content=working,container

This half is the textual content fragment:


#:~:textual content=working,container

This fragment finds the primary point out of ā€œworkingā€ (case-insensitive) on the web page and highlights every part from that time till it finds ā€œcontainerā€. There are a number of extra variants of the syntax. Learn the textual content fragments draft spec for particulars.

Search phrases might include delicate info that customers don’t wish to share with the vacation spot server. For good motive, search engines like google stopped reporting the consumer’s search phrases within the referer header a very long time in the past as a part of the widespread transfer to HTTPS. It could be dangerous if a brand new characteristic reintroduced this outdated knowledge leak.

The spec considers this concern. Textual content fragments are designed to be purely a browser-level characteristic — they’re not uncovered to JavaScript code. This screenshot demonstrates that doc.location.hash is clean as a result of Chromium stripped the textual content fragment away:


Screenshot of the JavaScript console in Chromium demonstrating that the destination page can’t see the text fragment
JavaScript code working within the vacation spot web page can’t see the textual content fragment.

I feel this the precise habits, however the spec authors appear to be contemplating altering it again as a result of it might constrain some legit use circumstances and since JavaScript can already decide what parts of a web page a consumer is studying by monitoring the viewport rect. I don’t know — exposing a delicate search time period appears extra invasive to me than the scroll place.

It’s price noting that the privateness concern exists for browsers that don’t assist textual content fragments: they’ll deal with the gibberish as a traditional URL fragment, which may simply be parsed with a little bit of JavaScript.

As a precaution, search engines like google and comparable websites ought to in all probability solely embrace textual content fragments of their hyperlinks if the consumer’s browser helps the characteristic (window.location.fragmentDirective).

Chrome is at present the one browser with textual content fragment assist. From what I’ve learn, the WebKit and Firefox groups are usually supportive of the concept however have some reservations about particular design decisions.

I hope this or one thing prefer it turns into extensively supported within the close to future.

Replace June 22, 2020: I uncared for to say fragmentations, an IndieWeb initiative that goals to resolve the identical downside and is no less than six years outdated. This characteristic makes use of regular URL fragments and client-side JavaScript to search out the matching textual content on the vacation spot web page (which is simply mandatory as a result of there’s no native browser assist, after all).

The post Linking to textual content fragments in internet pages – Ole Begemann appeared first on Tech TeTo.

]]>
https://techteto.com/linking-to-textual-content-fragments-in-internet-pages-ole-begemann/feed/ 0 2645
8 Finest Intermittent Fasting Apps That You Should Strive in 2021 https://techteto.com/8-finest-intermittent-fasting-apps-that-you-should-strive-in-2021/ https://techteto.com/8-finest-intermittent-fasting-apps-that-you-should-strive-in-2021/#respond Fri, 26 Nov 2021 14:17:47 +0000 https://techteto.com/8-best-intermittent-fasting-apps-that-you-must-try-in-2021/ November 26, 2021November 26, 2021 104007 Being an expert dietitian or health & wellness startup, in case you are planning to enter the fasting apps world, and planning to adapt an intermittent fasting way of life however unsure whether or not to maneuver forward with the concept or not. This weblog is for you. Herein, […]

The post 8 Finest Intermittent Fasting Apps That You Should Strive in 2021 appeared first on Tech TeTo.

]]>

104007

Being an expert dietitian or health & wellness startup, in case you are planning to enter the fasting apps world, and planning to adapt an intermittent fasting way of life however unsure whether or not to maneuver forward with the concept or not. This weblog is for you.

Herein, being an app improvement agency, we’ve curated an inventory of 8 greatest intermittent fasting apps that it’s essential to strive in 2021. So, let’s take a look on the high intermittent fasting apps.

Introduction

Intermittent fasting is blowing up on-line after a brand new examine discovered that folks on a weight loss plan had a lowered danger of coronary heart illness and a big metabolism enhance.

With the trending alternate day fasting, 16:8, 5:2, eat-stop-eat, the IF weight loss plan has boosted well being options. Being a weight loss plan specialist, you possibly can have interaction extra health-conscious individuals attempting to shed some pounds by means of your app improvement.

In case you are pondering of creating a fasting app, then that is the precise time. You may develop your personal fasting app with distinctive options, functionalities, and fascinating concepts to get your begin your intermittent fasting journey.

Planning to Create Well being and Health App?

Need to validate your app thought? Need to get a free session from an professional?

Finest Intermittent Fasting Apps

Right here is the record of greatest free weight monitoring apps and to make it simple for you, we’ve ready the record of greatest apps for intermittent fasting based mostly on their options, worth, and platform availability.

Nevertheless, all these free intermittent fasting apps are free to make use of, however it’s possible you’ll must pay for the subscriptions, in-app purchases, superior options, and consultations.

Now let’s focus on all these apps intimately to know extra about them and discover the explanation why these apps are one of the best.

  1. Zero

    Zero apps have over 1 million downloads and over 10 million full fasts up to now. It’s a easy intermittent fasting tracker that helps customers sync an intermittent quick with their organic clock. The app for fasting fetches the person’s location and figures out when the solar will set of their space.

    For instance, if the solar units at 6:30 PM, then you can begin fasting hours at 8:30 PM, and in between the Zero app will depend these 2 hours of nighttime consuming. This knowledge will retailer in your telephone and you may export it anytime in your private evaluation.

    This is likely one of the greatest intermittent fasting apps which might be freely obtainable to obtain for iOS and Android.

    best intermittent fasting app for 2020

    Picture Credit score: Zero

  2. LIFE Fasting Tracker

    From the various greatest fasting apps, the LIFE Fasting Tracker app is a scheduling tracker, for the reason that life fasting app permits customers to set their very own begin and finish instances & targets for the fasting durations.

    The advantage of the life fasting app is in-app studying libraries with research-based articles and suggestions for newbie and skilled intermittent fasters. The app has surpassed over 5,00,000 downloads since its launch in late 2018.

    That is one of the best free intermittent fasting app that has the fasting tracker on-line and it has recorded almost 7 million fasts up to now. It is likely one of the first well being options with a complicated tracker to waist circumference, glucose, and ketones. The fasting tracker additionally lets you supply intermittent fasting weight loss plan data, the place you get the weight loss plan in keeping with your physique kind.

    Moreover, in case you are on the keto weight loss plan, this app will assist you to to trace the length for which you might have been on ketosis.

    best intermittent fasting app for 2020

    Picture Credit score: Life Fasting Tracker

  3. BodyFast

    BodyFast app is a Germany-based on-line intermittent fasting plan platform. With its revolutionary and totally different fasting plans, it has been among the many high app for intermittent fasting.

    It permits customers to decide on a coach and comply with his meal planning suggestions. The person can improve and take up weekly challenges to remain aggressive and hold you motivated.

    The app has a particularly curated FAQs part that gives the solutions to a lot of the doable questions on IF for newcomers. The fasting tracker has over 8 million individuals up to now utilizing the app regularly.

    BodyFast App

    Picture Credit score: BodyFast

  4. Ate Meals Diary

    This social intermittent greatest fasting app is a visible meals diary, which helps in retaining monitor of how a lot time lapsed between meals and snacks.

    That is one of the best app for fasting which permits customers to share on social media, makes them look again on their decisions and the way they made them really feel.

    It’s the quickest and best meals journal and makes a person experiment with new habits, to see what works for a person. This makes Ate Meals Diary, one of the best meals monitoring app.

    best intermittent fasting app for 2020

    Picture Credit score: Ate Meals Diary

  5. Vora

    This app gives every day weight reduction targets, fasting hours, and your general progress. Vora is usually a nice weight reduction app in case you are on the lookout for an analogous characteristic in an app. Vora is a cloud-based greatest fasting app, because it permits customers to create, edit, and delete the fasts.

    Let’s customers view their final 7 fasts in a ravishing chart that exhibits their goal achievements. The Vora app permits customers to set the fasting program they like from full quick to five:2 to alternate day weight loss plan sorts. To this point, the app has over 3,00,000 fasters group.

    best intermittent fasting app for 2020

    Picture Credit score: Vora

    In accordance with Dr. Elizabeth Lowden ā€œAlternate-day fasting tends to incorporate each common meals consumption alternating with full fasting, that means no meals consumption in any respect, or a considerably diminished consumption of about 500 energy.ā€

  6. Fastient

    To take care of accountability whereas fasting a one meal plan and data of the meals consumption is important.

    The Fastient app has a large, open interface that leaves loads of room for a person’s journal; they’ll view knowledge in easy-to-read graphs and document their meals consumption simply by means of the fasting schedule tracker.

    best intermittent fasting app for 2020

    Picture Credit score: Fastient

  7. FastHabit

    Featured by GQ, The Guardian, and The Quick Firm, FastHabit is likely one of the high app for Intermittent Fasting.

    The app is for newcomers in addition to common customers who want to vary their app or begin fasting utilizing an app. It claims to tame your cravings and assist you to shed some pounds.

    FastHabit is a top-rated app on the iOS platform with 4.8 stars out of 5. It’s cherished by 1000’s of customers who’re captivated with intermittent fasting.

    fasthabit

    Picture Credit score: FastHabit

  8. Window

    The Window app is well personalized to trace your fasting and consuming window length, monitor weight reduction or positive aspects to encourage individuals. Additionally, you possibly can handle your weight discount targets from the app too.

    Select a plan for your self and outline your fasting time. Customise it accordingly in regards to the consuming length and begin time. Get notification when the consuming window is opened, after which you can begin your fasting.

    Window App

    Picture Credit score: Window

Steadily Requested Questions

That are one of the best intermittent fasting apps for iOS?

After contemplating the client evaluations of App Retailer, we’ve discovered that these 5 functions are one of the best intermittent fasting functions for iOS:

  1. Zero
  2. FastHabit
  3. Ate Meals Diary
  4. BodyFast
  5. LIFE Fasting

That are one of the best free fasting apps for Android?

After contemplating the Play Retailer’s buyer evaluations, we’ve discovered that the next functions are one of the best free app for intermittent fasting for Android:

  1. Zero
  2. Fastient
  3. BodyFast
  4. LIFE Fasting

How a lot weight can I lose after 15 days utilizing intermittent fasting?

Based mostly on the examine of ScienceDirect, after following intermittent fasting for 3-24 weeks, the approx physique weight diminished by 3 to eight%. After inspecting the speed of fasting and weight reduction, the general results of weight discount in an individual was discovered from 0.55 to 1.65 kilos per week.

Conclusion

In case you are an expert dietitian or working a health & wellness heart, on the lookout for one of the best ways to trace your buyer’s fasts and weight reduction progress, we’ve the apt app resolution within the type of a easy fasting app.

We’re specialised in well being and health app improvement. Test the most recent well being and health apps we’ve constructed for our shoppers.

  • Ryan Spiteri Health: Ryan Spiteri is all one health app which is well-known to take every day health traning.
  • ShotStats: ShotStats is a health app for tennis gamers to dictate their enjoying photographs and magnificence.

Being a number one iPhone app improvement firm, we’ve developed cell apps in virtually each style, from taxi to meals supply to well being and health.

Listed below are a few of the information that can assist you to distinguish us from the opposite main cell app improvement corporations.

Why-Space-O-Technologies

Nonetheless have any confusion or question concerning constructing one of the best app for intermittent fasting, the fee to develop a cell app for fasting, IF app improvement timeline, and methods to create an app, simply fill our contact us type. Considered one of our gross sales representatives will get again to you shortly. The session is freed from price.

The post 8 Finest Intermittent Fasting Apps That You Should Strive in 2021 appeared first on Tech TeTo.

]]>
https://techteto.com/8-finest-intermittent-fasting-apps-that-you-should-strive-in-2021/feed/ 0 2600
Fashion SwiftUI Buttons in iOS 15 https://techteto.com/fashion-swiftui-buttons-in-ios-15/ https://techteto.com/fashion-swiftui-buttons-in-ios-15/#respond Fri, 26 Nov 2021 13:16:17 +0000 https://techteto.com/how-to-style-swiftui-buttons-in-ios-15/ In iOS 15, Apple launched a brand new strategy to customise buttons in iOS apps for each SwiftUI and UIKit frameworks. Whereas this tutorial focuses on the brand new options of SwiftUI, you may check with this improbable article, written by Sarun, about the best way to fashion UIButton in iOS 15. Styling a Button […]

The post Fashion SwiftUI Buttons in iOS 15 appeared first on Tech TeTo.

]]>

In iOS 15, Apple launched a brand new strategy to customise buttons in iOS apps for each SwiftUI and UIKit frameworks. Whereas this tutorial focuses on the brand new options of SwiftUI, you may check with this improbable article, written by Sarun, about the best way to fashion UIButton in iOS 15.

Styling a Button in SwiftUI

Earlier than we dive into the brand new modifiers launched in iOS 15, let’s revisit how we fashion a button within the present model of iOS.

swiftui-button-in-ios-15

Let’s say, we need to create a button with rounded corners, we write the code like this:

We customise the button’s foreground and background colour, apply paddings, and spherical its corners utilizing the .clipShape modifier.

In iOS 15, to create an analogous button with rounded corners, you should use a brand new modifier known as buttonBorderShape and apply a brand new fashion known as BorderedProminentButtonStyle like this:

By making use of the .borderedProminent fashion, iOS renders the button with purple background and show the textual content in white. The .buttonBorderShape modifier enables you to set the border form of the button. Right here, we set it to .roundedRectangle to around the button’s corners.

Management Measurement for Buttons

The .controlSize means that you can change the dimensions of the button. The default measurement is .common. Different legitimate values contains .giant, .small, and .mini. The determine under reveals you the way the button seems to be for various sizes.

swiftui-buttons-control-size

Button Border Form

Apart from utilizing .roundedRectangle, SwiftUI supplies one other border form named .capsule for builders to create a capsule form button.

swiftui-button-border-shape

You may as well use the .automated choice to let the system modify the form of the button.

Altering the Button Fashion

Up to now, we use the .borderProminent button fashion. The brand new model of SwiftUI supplies different built-in types together with .bordered, .borderless, and .plain. The .bordered fashion is the one you’ll often use. The determine under shows a pattern button utilizing the .bordered fashion in each gentle and darkish modes.

swiftui-button-style

In fact, you may create the identical button utilizing your individual implementation. This new fashion, launched in iOS 15, saves you time from writing your individual code.

Making use of Fashion to A number of Buttons

With button fashion, you may simply apply the identical fashion to a bunch of buttons. Right here is an instance:

Utilizing Button Position

The iOS 15 model of the SwiftUI framework introduces a brand new function possibility for Button. This feature describes the semantic function of the button. Primarily based on the given function, iOS routinely renders the suitable look & really feel for the button.

For instance, when you outline the function as .harmful like this:

iOS will show the delete button in crimson routinely. The next determine reveals you the looks of the button for various roles and button types:

swiftui-button-role

Affirmation Dialog

Apart from the brand new button fashion, iOS 15 comes with a brand new modifier known as .confirmationDialog which you could connect to a Button for displaying a affirmation dialog.

Here’s a pattern code snippet for presentating the dialog:

The .confirmationDialog modifier takes in a title and a binding to a Boolean worth that determines whether or not to current the dialog. Optionally, you may point out whether or not the dialog ought to show the title.

With the code above, the affirmation dialog will likely be introduced just like the determine under.

swiftui-confirmation-dialog

Customizing the Button with Supplies

In iOS 15, SwiftUI introduces a fabric kind for builders to create various kinds of blur results. You possibly can apply a blur impact to a view that seems behind one other view by including one of many following supplies utilizing the .background modifier:

  • .ultraThickMaterial
  • .thickMaterial
  • .regularMaterial
  • .thinMaterial
  • .ultraThinMaterial

Right here is the pattern code snippet which applies the .ultraThinMaterial:

As defined by Apple, including a fabric is like inserting a translucent layer between the modified view and its background. Relying on the fabric you employ, it is going to obtain a distinct blur impact. The next determine demonstrates the blur impact of various supplies.

swiftui-background-material

Toggle Button

swiftui-toggle

Toggle in iOS seems within the type of change. In iOS 15, you may configure a toggle to seem like a button through the use of the .toggleStyle modifier like this:

By setting the toggle fashion to .button, the toggle seems like a button. The determine under reveals the way it seems to be when the toggle is in ON/OFF state.

swiftui-toggle-button-ios-15

Abstract

iOS 15 brings quite a lot of enhancements for customizing SwiftUI buttons. When you can create your individual resolution to fashion a button, the brand new model of SwiftUI makes builders’ job even simpler with some built-in types.

The one draw back of all these new options is which you could solely use them in iOS 15. In case your apps require to assist older variations of iOS, you have to to fashion the button with your individual implementation.



The post Fashion SwiftUI Buttons in iOS 15 appeared first on Tech TeTo.

]]>
https://techteto.com/fashion-swiftui-buttons-in-ios-15/feed/ 0 2552
iPadOS 15 Tutorial: What’s New for Builders https://techteto.com/ipados-15-tutorial-whats-new-for-builders/ https://techteto.com/ipados-15-tutorial-whats-new-for-builders/#respond Fri, 26 Nov 2021 12:12:47 +0000 https://techteto.com/ipados-15-tutorial-whats-new-for-developers/ Whereas tablets don’t appear excessive precedence for many platform or system makers, Apple by no means stops bettering iPad’s {hardware} and software program. In 2019, Apple renamed the pill’s working system iPadOS, emphasizing its distinctive multitasking and keyboard help. Persevering with Apple’s two-year cycle of appreciable iPadOS updates, iPadOS 15 presents many enhancements. On this […]

The post iPadOS 15 Tutorial: What’s New for Builders appeared first on Tech TeTo.

]]>

Whereas tablets don’t appear excessive precedence for many platform or system makers, Apple by no means stops bettering iPad’s {hardware} and software program. In 2019, Apple renamed the pill’s working system iPadOS, emphasizing its distinctive multitasking and keyboard help. Persevering with Apple’s two-year cycle of appreciable iPadOS updates, iPadOS 15 presents many enhancements.

On this tutorial, you’ll find out about enhancements in iPadOS 15, together with:

  • Multitasking enhancements
  • Keyboard shortcuts enhancements
  • Pointer updates

You’ll do that whereas modernizing the app NotesLite, which you should use to put in writing notes and add photographs.

Getting Began

Obtain the starter undertaking by clicking the Obtain Supplies button on the prime or backside of the tutorial.

The starter undertaking incorporates a completely practical app with options launched for iPadOS 14 and beneath. You’ll enhance the app by including new options launched in iPadOS 15 and making it look extra fashionable and practical.

A number of Home windows or Scenes

In iPadOS 13, Apple launched the idea of scenes to help a number of home windows in iPad apps.

Home windows are represented by UIScene cases. A UISceneSession manages a scene. All through this tutorial, if you see a scene or UISceneSession, you possibly can consider it as a window.

Should you constructed an app earlier than iOS 13, you recognize AppDelegate is the one place that does all the things associated to app launch, foregrounding, backgrounding and extra.

In iOS 13, Apple moved a few of AppDelegateā€˜s tasks to SceneDelegate.

These days, utility entry factors are inside AppDelegate, and window-related stuff — similar to backgrounding, foregrounding and URL dealing with — are inside an object conforming to UISceneDelegate or UIWindowSceneDelegate.

These additionally apply to iPhone apps. You’ll be able to consider an iPhone app as a single window utility.

Every scene wants an occasion of UISceneConfiguration for its configuration. You outline these configurations inside Information.plist.

Now, you’ll see how all these join contained in the starter undertaking.

Exploring NotesLite

Open the starter undertaking and select an iPad goal. Then, construct and run.

NotesLite first run.

The picture above exhibits how the app works out of the field.

Faucet the plus button so a brand new window seems on the aspect. Write your be aware, add an image and faucet Save. The creation window closes and the newly added be aware seems within the sidebar. Tapping the be aware within the sidebar will present the element web page on the precise.

Be aware: Generally including a picture within the simulator doesn’t work as anticipated. If this occurs, strive including a unique picture or connecting your iPad and testing on system.

The app already helps a number of home windows. Check out the file construction:

NotesLite file and folder structure in Xcode

Contained in the Scenes folder are the three subclasses for UIWindowSceneDelegate:

  • First, there’s SceneDelegate for the default window of the app.
  • Then, there’s CreateSceneDelegate for the be aware creation window.
  • Lastly, there’s DetailSceneDelegate for the be aware element window.

Whenever you opened the app, the default window appeared. After tapping the plus button, CreateSceneDelegate took over. You’ll add help for a element window later within the tutorial.

Contained in the Supporting Recordsdata folder, open Information.plist.

There’s a key known as Software Scene Manifest whose worth is already within the starter undertaking. It is advisable outline every scene configuration your app helps inside this key.

Info.plist for NotesLite app, showing the scene manifest key.

As you possibly can see within the screenshot above, you should outline no less than the Configuration Identify and the Delegate Class Identify to which this configuration relates.

NSUserActivity

In iOS 8, Apple launched a category known as NSUserActivity. At first, you would use this class to combine the Handoff characteristic between units.

Annually, this class turned extra highly effective. There’s even a operating joke in the neighborhood that Apple would possibly sooner or later deprecate all iOS APIs and launch all the things below NSUserActivityā€˜s tent.

As of iOS 15, you possibly can — and will — use NSUserActivity in the event you help any of those options:

  • Handoff
  • In-app Highlight search
  • Siri and Shortcuts Intents
  • A number of home windows on iPad

Whenever you wish to open a brand new window inside your app, ask the system to create a scene utilizing requestSceneSessionActivation(_:userActivity:choices:errorHandler:) on UIApplicationā€˜s shared object.

Nonetheless, you possibly can’t straight specify a scene identify right here. You do that utilizing NSUserActivity. The system offers you again this occasion, and you may resolve which scene to configure and current.

Window Presentation Type

On iPadOS 14 and earlier, the person interface for managing an app’s home windows was so hidden and tough to make use of that even some professional customers prevented it. Fortuitously, on iPadOS 15, this UI is significantly better.

On the prime of every app that helps Cut up View and Slide Over, there’s a brand new button represented by three dots. With NotesLite open, faucet it.

Possible actions of three dots menu

Three buttons seem. This allows you to put the window in Full Display screen, Cut up View or Slide Over with out going by way of the trouble of dragging and dropping. Hurray!

Nonetheless, these aren’t the one choices accessible. In iPadOS 15, Apple added a brand new fashion to the window modes: Distinguished.

It seems a like a Kind Sheet at first, however you possibly can simply put it in another mode. Now, it’s time so as to add it to the app.

Open NotesListViewController.swift contained in the UI group. Go to openNewNote(). Right here’s what it seems like:


@objc func openNewNote() {
  // 1
  if UIDevice.present.userInterfaceIdiom == .pad {
    // 2
    let userActivity = ActivityIdentifier.create.userActivity()

    // 3
    let choices = UIWindowScene.ActivationRequestOptions()
    choices.preferredPresentationStyle = .customary

    // 4
    UIApplication.shared.requestSceneSessionActivation(
      nil,
      userActivity: userActivity,
      choices: choices,
      errorHandler: nil)
  } else {
    let navigationController = UINavigationController(
      rootViewController: NoteViewController.storyboardInstance)
    current(navigationController, animated: true)
  }
}

Right here’s what this does:

  1. Since iPhone apps don’t help a number of scenes, partition primarily based on the system the code is operating on.
  2. Create a userActivity utilizing a helper technique from SceneConfigurations.swift.
  3. Subsequent, present the system with some activation choices. The system tries to contemplate these requests when activating a scene. This code asks the system to indicate a customary presentation fashion. This fashion is what made the creation window seem alongside the principle window. On iPadOS 15, this feature defaults to automated, and the system decides what works greatest.
  4. Request a scene activation with the person exercise and the request choices. This makes the brand new window seem.

Now, change the popular presentation fashion line to this:


choices.preferredPresentationStyle = .distinguished

Construct and run. Then, faucet the plus button.

Launching note creation window in prominent window style

A brand new window seems on prime of the present view.

There’s a tiny indicator that exhibits this isn’t a kind sheet or a standard modal presentation: the three dots button on the highest.

Faucet it, and also you’ll see a brand new choice:

All four possible window modes on iPadOS 15 under the three dots button.

The icon speaks for itself. You requested the system to current this window prominently.

The three dots button does one other job, too. This time, as an alternative of tapping it, strive swiping it down. Should you look carefully, the window goes someplace on the backside of the display. This space is the App Shelf. It’s a spot the place you possibly can see all open home windows for an app and change between them.

If an app has a number of lively home windows, if you open it from House Display screen, the shelf seems for a break up second. It’s also possible to summon the shelf at any time by tapping on the three dots button. Shut the home windows from the shelf by swiping up.

Right here’s a GIF for instance these interactions:

App Shelf interactions

Subsequent, you’ll find out about activation actions.

Activation Motion

Per Apple’s pointers, you solely have to open new home windows in your app primarily based on the person’s specific interplay. As you possibly can implement many of those interactions utilizing UIAction, Apple supplied a code shortcut.

In NotesListViewController.swift, go to configureBarButtonItems(). Then, create an motion that calls openNewNote(), and fasten it to the bar button merchandise.

Do that by changing the present configureBarButtonItems() with this:


non-public func configureBarButtonItems() {
  // 1
  let addAction = UIAction { _ in
    let navigationController = UINavigationController(
      rootViewController: NoteViewController.storyboardInstance)
    self.current(navigationController, animated: true)
  }

  // 2
  let newSceneAction = UIWindowScene.ActivationAction(
    alternate: addAction
  ) { _ in
    // 3
    let userActivity = ActivityIdentifier.create.userActivity()

    let choices = UIWindowScene.ActivationRequestOptions()
    choices.preferredPresentationStyle = .distinguished

    // 4
    return UIWindowScene.ActivationConfiguration(
      userActivity: userActivity, 
      choices: choices)
  }

  // 5
  navigationItem.rightBarButtonItem = UIBarButtonItem(
    systemItem: .add,
    primaryAction: newSceneAction,
    menu: nil)
}

Right here’s what this does:

  1. First, create a UIAction that presents NoteViewController modally.
  2. Subsequent, create an occasion of UIWindowsScene.ActivationAction. Because the identify implies, you utilize it for activating a scene. Go the addAction you created in step 1 as a parameter to this operate. UIKit robotically runs the alternate motion when the system doesn’t help a number of home windows. How handy is that?
  3. Then, create a person exercise for the be aware creation scene and configure the request choices. You’re already acquainted with this step.
  4. Right here, you come back an occasion of UIWindowScene.ActivationConfiguration, passing the person exercise and choices. It’s like if you handed this stuff to requestSceneSessionActivation(_:userActivity:choices:errorHandler:).
  5. Since newSceneAction is definitely an occasion of UIAction, you set it as the first motion of the bar button merchandise.

Construct and run. Then, strive tapping the plus icon. If nothing adjustments, it means you have been profitable.

Activation Interplay

Whereas on iPadOS 14 and beneath, Apple insisted on Drag & Drop as the method to open a brand new window, on iPadOS 15, it advertises context menus and a brand new pinch open gesture. Apple additionally built-in these in its personal apps. As an illustration, open the Notes app.

Within the sidebar, you possibly can contact and maintain or right-click with a mouse or trackpad to open the context menu. Selecting Open In New Window will open a be aware in a brand new window with the distinguished fashion you noticed earlier.

Open In New Window option in Notes app context menu.

It’s also possible to pinch open with two fingers on any merchandise within the sidebar to open it in a brand new window, prominently.

Subsequent, you’ll add these choices to NotesLite.

Context Menu

In NotesListViewController.swift, scroll to the mark line // MARK: - UICollectionViewDelegate.

Take a look at collectionView(_:contextMenuConfigurationForItemAt:level:). This technique provides context menu objects for every row. For now, it solely incorporates delete. You’ll add a brand new motion for opening the be aware in a brand new window.

First, although, you should create a helper technique for configuration, which you’ll use within the subsequent step. Add this inside NotesListViewController slightly below the definition of `deleteItem(at:)`:


non-public func activationConfiguration(
  for indexPath: IndexPath
) -> UIWindowScene.ActivationConfiguration? {
  // 1
  guard let be aware = dataSource.itemIdentifier(for: indexPath) else {
    return nil
  }
  // 2  
  var information: [String: Any] = [
    NoteUserInfoKey.id.rawValue: note.id,
    NoteUserInfoKey.content.rawValue: note.content
  ]

  // 3
  if let knowledge = be aware.picture?.jpegData(compressionQuality: 1) {
    information[NoteUserInfoKey.image.rawValue] = knowledge
  }

  // 4
  let userActivity = ActivityIdentifier.element.userActivity(userInfo: information)

  let choices = UIWindowScene.ActivationRequestOptions()
  choices.preferredPresentationStyle = .distinguished

  let configuration = UIWindowScene.ActivationConfiguration(
    userActivity: userActivity,
    choices: choices)
  return configuration
}

It seems fairly lengthy; nonetheless, it’s fairly easy:

  1. Get the be aware pertaining to the indexPath from the collectionViewā€˜s dataSource. It could return nil, so use guard-let syntax and exit the tactic early if the index is nil.
  2. The way in which to cross knowledge to the system for creating a brand new window is thru person actions. Every person exercise has userInfo, in which you’ll retailer property record knowledge. Since userInfo makes use of a string-based key-value dictionary, lower potential errors by utilizing some predefined keys, that are contained in the starter undertaking. Right here, you retailer the be aware’s id and content material.
  3. Examine if the be aware has an related picture. In that case, compress it to JPEG and reserve it to userInfo as Knowledge.
  4. Like earlier than, create a person exercise, set the request choices and return a configuration made with them.

Now, return to // MARK: - UICollectionViewDelegate and substitute let actions = [delete] with the next:


// 1
var actions = [delete]

// 2
if let configuration = self.activationConfiguration(for: indexPath) {
  // 3
  let newSceneAction = UIWindowScene.ActivationAction { _ in
    return configuration
  }
  
  // 4
  actions.insert(newSceneAction, at: 0)
}

Within the code above, you:

  1. Change actions from a let to a var, so you possibly can add objects later.
  2. Get an occasion of UIWindowScene.ActivationConfiguration utilizing activationConfiguration(for:), which you’ll write later. Since it could be nil in sure instances, you conditionally unwrap it.
  3. Create a brand new activation motion as you probably did earlier, after which return the configuration you bought from step 2.
  4. Insert newSceneAction on the prime of actions.

As within the authentic code, this returns a menu utilizing the desired actions.

Construct and run. Invoke the context menu within the notes record by touching and holding or right-clicking. It’s possible you’ll now open the be aware in a brand new window.

Open In New Window option in NotesLite context menu.

Note detail page opened in a new window prominently.

Subsequent, you’ll add pinch help on UICollectionView objects.

Pinching

First, implement a brand new delegate technique. Add this on the finish of NotesListViewController.swift, simply earlier than the closing brace:


override func collectionView(
  _ collectionView: UICollectionView,
  sceneActivationConfigurationForItemAt
  indexPath: IndexPath,
  level: CGPoint
) -> UIWindowScene.ActivationConfiguration? {
  activationConfiguration(for: indexPath)
}

You come an activation configuration for every merchandise you’d wish to help pinching.

Construct and run. Then, strive pinching open on a be aware.

Pinch on a note in the sidebar

All the row will get greater whilst you pinch. You’ll be able to customise the transition in a means that solely the picture scales up. To do that, inform the system on which view the size transition ought to happen.

Open activationConfiguration(for:), and proper earlier than the return configuration line, add:


// 1
if let cell = collectionView.cellForItem(at: indexPath) {
  // 2
  if let imageView = cell.contentView.subviews.first(
    the place: { subview in
      (subview as? UIImageView)?.picture != nil
    }
  ) {
    // 3
    configuration.preview = UITargetedPreview(view: imageView)
  }
}

Right here’s what this does:

  1. First, get the cell the person pinched.
  2. Discover the imageView contained in the subviews of the cell’s contentView the place picture isn’t nil.
  3. Set the imageView you present in step 2 because the preview of the activation configuration.

Construct and run. Strive pinching another time. It seems rather more polished.

Pinch on the note in the sidebar. Transition begins from the image.

Be aware: To help this pinch gesture on views aside from cells in a UICollectionView, create a UIWindowScene.ActivationInteraction and fasten it to a customized view anyplace within the hierarchy. It’s straightforward to do, however past the scope of this tutorial.

Saving and Restoring State in Scenes

Offering polished, handy methods to open content material in new home windows is essential. Nonetheless, it’s equally essential to avoid wasting and restore the scene’s state to have the ability to return to it seamlessly.

When a scene strikes to the background, the system asks the scene’s delegate for an occasion of NSUserActivity to characterize its state.

For one of the best expertise, the scene state shouldn’t solely save the content material, but additionally the visible and interplay state similar to scroll and cursor place.

It’s best to save and restore state for all of your app’s scenes, however for brevity, you’ll learn to save and restore the state just for the be aware creation window.

To make saving and restoring simpler, Apple launched two new strategies in UISceneDelegate and its inherited object, UIWindowSceneDelegate.

Open CreateSceneDelegate.swift and add:


func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? {
  // 1
  guard
    let navigationController = window?.rootViewController 
      as? UINavigationController,
    let noteVC = navigationController.viewControllers.first 
      as? NoteViewController 
  else {
    return nil
  }

  // 2
  let stateActivity = ActivityIdentifier.create.userActivity()

  // 3
  var information: [String: Any] = [
    NoteUserInfoKey.content.rawValue: noteVC.textView.text ?? "",
    NoteUserInfoKey.contentInteractionState.rawValue: 
      noteVC.textView.interactionState
  ]
  if let picture = noteVC.selectedImage?.jpegData(compressionQuality: 1) {
    information[NoteUserInfoKey.image.rawValue] = picture
  }

  // 4
  stateActivity.addUserInfoEntries(from: information)

  return stateActivity
}

The system calls this technique to avoid wasting the state for a scene. It returns a person exercise, which the system provides again to you if you wish to restore the state.

Right here, you:

  1. Attempt to discover the occasion of NoteViewController, which is within the view hierarchy. If there isn’t any, you don’t have something to avoid wasting, so return nil.
  2. Create an empty person exercise for the be aware creation web page, as you probably did if you wished to request a brand new window.
  3. Retailer the values of the textual content and interactionState properties of textView into the userInfo dictionary. interactionState is a brand new property of UITextField and UITextView on iPadOS 15 that allows you to save and restore cursor and scroll place. You additionally save the picture as Knowledge if it’s accessible.
  4. Add the contents of the information dictionary to the person exercise and return it.

To revive the state, implement the tactic beneath, extracting the information you saved into the person exercise and restoring it within the respective views. Add this technique beneath the tactic you simply added in CreateSceneDelegate.swift:


func scene(
  _ scene: UIScene, 
  restoreInteractionStateWith stateRestorationActivity: NSUserActivity
) {
  // 1
  guard
    let navigationController = window?.rootViewController 
      as? UINavigationController,
    let noteVC = navigationController.viewControllers.first 
      as? NoteViewController,
    let userInfo = stateRestorationActivity.userInfo 
  else {
    return
  }

  // 2
  noteVC.viewType = .create

  // 3
  let picture: UIImage?
  if let knowledge = userInfo[NoteUserInfoKey.image.rawValue] as? Knowledge {
    picture = UIImage(knowledge: knowledge)
  } else {
    picture = nil
  }

  // 4
  let textual content = userInfo[NoteUserInfoKey.content.rawValue] as? String
  noteVC.textView.textual content = textual content ?? ""
  noteVC.selectedImage = picture

  // 5
  if let interactionState = 
    userInfo[NoteUserInfoKey.contentInteractionState.rawValue] {
      noteVC.textView.interactionState = interactionState
  }
}

Within the code above:

  1. First, you verify if the system has completed establishing the view controllers. You additionally verify if there’s any userInfo accessible to revive.
  2. Subsequent, you set the viewType of NoteViewController to .create. As you will have observed, NoteViewController is used for each creating and viewing a be aware.
  3. Then, you verify if picture knowledge is out there inside userInfo. If it’s there and you may create a UIImage from it, you retailer its picture variable.
  4. Subsequent, you set the contents of textView and selectedImage.
  5. Lastly, after setting textual content on UITextView, you set interactionState if it’s accessible. At all times set the interplay state after setting the content material.

That’s it. Construct and run.

Steps to trigger save and restore in a scene.

Now, observe these directions to see the save and restore mechanism in motion:

  1. Run the app from Xcode.
  2. Faucet the plus button.
  3. Add some textual content and maybe a picture.
  4. Transfer the cursor to someplace aside from the tip of the textual content.
  5. Swipe down on the three dots button of the note-creating window to attenuate it to the shelf.
  6. Kill the app from Xcode utilizing the Cease button. It will simulate the state of affairs the place the system kills the app course of.
  7. Run the app once more from Xcode.
  8. Faucet the New Be aware window from the shelf.
  9. Every thing is there, even the cursor place.

Within the subsequent part, you’ll find out about keyboard enhancements.

Keyboard Shortcuts Enhancements

One attribute of a Mac app is its Menu Bar, a single place containing each potential motion for the app. After Apple began embracing the {hardware} keyboard for iPad, many individuals wished for a menu bar on iPad. On iPadOS 15, Apple fulfilled this want — type of!

Apps on iPad received’t get a persistent menu bar like Mac apps. Somewhat, if you maintain Command on the {hardware} keyboard linked to the iPad, you’ll get a brand new menu system that appears just like the Mac implementation.

Listed below are a number of the options of this new system:

  1. Apps can categorize actions into teams.
  2. Customers can seek for accessible actions, similar to on macOS.
  3. The system robotically hides inactive actions as an alternative of disabling them.
  4. The API is just like the one used to create menu objects for a Catalyst app. In consequence, you don’t have to duplicate issues when including keyboard shortcuts for iPad and Mac Catalyst.

In NotesLite, there are a few keyboard shortcuts accessible.

Particularly, NoteViewController incorporates Save and Shut actions triggered by Command-S and Command-W. In NotesListViewController, you possibly can create a brand new be aware by urgent Command-N.

See the shortcut motion teams accessible proper now in NotesLite by holding the Command key:

Uncategorized keyboard shortcuts

The class for the motion is the identify of the app. When the builders of an app use the outdated mechanism for offering keyboard shortcuts, that is the way it seems. Subsequent, you’ll replace to the trendy method.

Updating to the Menu Builder API

One of many outdated methods of including keyboard shortcuts help was overriding the keyCommands property of UIResponder. Since UIViewController is a UIResponder, you are able to do this in view controllers.

There are two occurrences of keyCommands in NotesLite. In NoteViewController.swift, you’ll see:


override var keyCommands: [UIKeyCommand]? {
  [
    UIKeyCommand(title: "Save", action: #selector(saveNote), 
      input: "s", modifierFlags: .command),
    UIKeyCommand(title: "Close", action: #selector(dismiss), 
      input: "w", modifierFlags: .command)
  ]
}

Take away keyCommands from NotesListViewController.swift and NoteViewController.swift. You need to use Xcode’s Discover characteristic.

Apple recommends defining all menu objects in your app at launch. To take action, open AppDelegate.swift.

Override buildMenu(with:), which is a technique on UIResponder:


override func buildMenu(with builder: UIMenuBuilder) {
  tremendous.buildMenu(with: builder)

  // 1
  guard builder.system == .essential else { return }

  // 2
  let newNoteMenu = UIMenu(
    choices: .displayInline,
    youngsters: [
      UIKeyCommand(
        title: "New Note",
        action: #selector(NotesListViewController.openNewNote),
        input: "n",
        modifierFlags: .command)
    ])

  // 3
  let saveMenu = UIMenu(
    choices: .displayInline,
    youngsters: [
      UIKeyCommand(
        title: "Save",
        action: #selector(NoteViewController.saveNote),
        input: "s",
        modifierFlags: .command)
    ])

  // 4
  let closeMenu = UIMenu(
    choices: .displayInline,
    youngsters: [
      UIKeyCommand(
        title: "Close",
        action: #selector(NoteViewController.dismiss),
        input: "w",
        modifierFlags: .command)
    ])

  // 5
  builder.insertChild(newNoteMenu, atStartOfMenu: .file)
  builder.insertChild(closeMenu, atEndOfMenu: .file)
  builder.insertChild(saveMenu, atEndOfMenu: .file)
}

Within the code above, you:

  1. Examine if the system is looking the menu builder API for the essential menu bar.
  2. Create UIMenu cases for all objects you need within the menu bar. Right here, you’re making a menu merchandise known as New Be aware with the keyboard shortcut Command-N. The selector for this motion is openNewNote() inside NotesListViewController.
  3. Make a menu merchandise for saving a be aware. This time, the set off is inside NoteViewController.
  4. Create a menu merchandise for closing the be aware window.
  5. Put menu objects in numerous system-defined teams, similar to File and Edit. You’ll be able to create a brand new class in the event you need.

Construct and run. Faucet the plus button or press Command-N, after which maintain the Command key.

Categorized keyboard shortcuts for note creation window

The system even added textual content enhancing shortcuts below the Edit menu at no cost. Who doesn’t like free stuff?

Be aware: If the shortcuts don’t seem, ensure you’re returning true in utility(_:didFinishLaunchingWithOptions:) in AppDelegate.

Conditionally Disabling Sure Actions

There’s a small challenge, although. What if you wish to conditionally disable sure actions? As an illustration, the Save motion doesn’t make sense when the NoteViewController isn’t in create mode.

To resolve this, override one other UIResponder technique known as canPerformAction(_:withSender:). Whenever you return true right here, the motion works; in any other case, it’ll get ignored. Add this technique inside NoteViewController proper after viewDidLoad():


override func canPerformAction(
  _ motion: Selector, 
  withSender sender: Any?
) -> Bool {
  if motion == #selector(dismiss) { // 1
    return splitViewController == nil
  } else if motion == #selector(saveNote) { // 2
    return viewType == .create
  } else { // 3
    return tremendous.canPerformAction(motion, withSender: sender)
  }
}

Within the code above:

  1. The system calls this any time a selector reaches this view controller within the responder chain. In consequence, you should verify for motion to behave primarily based on the enter. If it’s the dismiss selector, return true provided that splitViewController is nil. Should you offered this web page inside a brand new window, there can be no UISplitViewController concerned. Urgent Command-W will kill the app in the event you don’t do that verify.
  2. If the motion is saveNote, verify whether or not this view controller is in create mode.
  3. In any other case, let the system resolve.

Construct and run.

Hiding unrelated keyboard shortcuts in note detail page

Open a be aware in a brand new window, and maintain the Command key. This time, the Save motion isn’t there anymore.

Pointer Enhancements

Apple launched pointer help in iPadOS 13.4. This yr, it acquired its first set of enhancements.

Band Choice

The primary addition is band choice, a brand new pointer-specific multi-selection expertise acquainted to Mac customers.

In iPadOS 15, if you click on and drag in a non-list UICollectionView, the pointer stretches right into a rectangle, and the gathering view selects the objects the rectangle encompasses.

Any UICollectionView that helps the present one and two-finger multi-selection gestures by way of the shouldBeginMultiple Choice Interplay API will get this habits robotically in iPadOS 15.

For something aside from a UICollectionView, the brand new UIBandSelectionInteraction API lets you simply undertake this expertise.

Right here’s a GIF from the Recordsdata app:

Band selection in Files app on iPadOS 15

Pointer Equipment

The second addition to the system pointer is the power to connect equipment.

In iPadOS 14 and earlier, you would present a customized form for the pointer in the event you desired. Nonetheless, for many use instances, you solely want so as to add sure equipment across the system pointer.

Should you look carefully on the be aware element web page, there’s a deal with on the backside of the picture. Should you contact and drag it, you possibly can resize the picture. You’ll add equipment to the pointer, so it’s clearer which you can resize the picture vertically.

Resizing the image without pointer interactions

In NoteViewController.swift, discover dragHandler. On the finish of the didSet block, add:


let interplay = UIPointerInteraction(delegate: self)
dragHandler.addInteraction(interplay)

This creates a brand new pointer interplay, units the NoteViewController as its delegate and provides it to the interactions record of dragHandler.

To silence the compiler’s nagging, on the finish of the present file, add this:


extension NoteViewController: UIPointerInteractionDelegate {
  // 1
  func pointerInteraction(
    _ interplay: UIPointerInteraction, 
    styleFor area: UIPointerRegion
  ) -> UIPointerStyle? {
    // 2
    let preview = UITargetedPreview(view: dragHandler)

    // 3
    let fashion = UIPointerStyle(impact: .carry(preview))

    // 4
    fashion.equipment = [
      .arrow(.top),
      .arrow(.bottom)
    ]

    // 5
    area.latchingAxes = .vertical

    return fashion
  }
}

Within the code above, you:

  1. Override pointerInteraction(_:styleFor:). The system consults this technique for a pointer’s fashion on a sure view.
  2. Create a focused preview with dragHandler. You already know this API because you used it to customise the pinch transition.
  3. Create a pointer-style object with the carry impact. Different choices are spotlight and hover. Carry seems greatest for this interplay.
  4. Add equipment across the pointer. Right here, you added two arrows to the highest and backside of the pointer. You’re not restricted to this, although. One can use a customized form with a customized place.
  5. Being able to set latchingAxes is new this yr. When set, the fashion related to this area will lock in and permit free-form motion alongside the desired axes.

Lastly, construct and run. Should you’re testing within the simulator, choose Enter ā–ø Ship Pointer to System from the I/O menu.

Resizing the image with pointer interactions and accessories.

Look how cool the pointer interplay is!

The place to Go From Right here?

You’ll be able to obtain the finished undertaking information by clicking Obtain Supplies on the prime or backside of this tutorial.

When you’ve completed rather a lot in the present day, iPadOS 15 is a stable launch and there’s extra to study.

Listed below are some locations to seek the advice of:

We hope you loved this tutorial. When you’ve got any questions or feedback, please be part of the discussion board dialogue beneath!

The post iPadOS 15 Tutorial: What’s New for Builders appeared first on Tech TeTo.

]]>
https://techteto.com/ipados-15-tutorial-whats-new-for-builders/feed/ 0 2507
Add a number of targets to swift undertaking – iOSTutorialJunction https://techteto.com/add-a-number-of-targets-to-swift-undertaking-iostutorialjunction/ https://techteto.com/add-a-number-of-targets-to-swift-undertaking-iostutorialjunction/#respond Fri, 26 Nov 2021 10:00:07 +0000 https://techteto.com/add-multiple-targets-to-swift-project-iostutorialjunction/ Including a number of targets to swift undertaking is a necessity of hour. For instance, in case your app level to completely different finish factors. One finish level is pointing to improvement server and second endpoint is for manufacturing or stay server, then commonest strategy for a newbie iOS developer is to remark out completely […]

The post Add a number of targets to swift undertaking – iOSTutorialJunction appeared first on Tech TeTo.

]]>

Including a number of targets to swift undertaking is a necessity of hour. For instance, in case your app level to completely different finish factors. One finish level is pointing to improvement server and second endpoint is for manufacturing or stay server, then commonest strategy for a newbie iOS developer is to remark out completely different finish factors whereas producing builds for particular setting. Creating particular person targets for various configurations saves iOS builders from this headache of commenting and uncommenting code for various configurations/settings.

Why we have to add a number of targets in swift

  • If our app is utilizing completely different servers finish factors
  • Single app goes for use for various customers(instance buyer consumer and admin consumer)
  • Must made two app model (Free and Paid)

Steps so as to add a number of targets in swift

1. Create a reproduction goal as proven in picture

Create a duplicate target

2.Rename this duplicate goal. We renamed it to Manufacturing. Similar change identify of information.plist file created by xcode for our manufacturing goal.

Changing info.plist name for our new target

3.Point out similar identify in construct setting of Manufacturing goal.

Changing plist name in build setting of our new target

4. Add swift flag for our targets as proven in beneath picture. Flags are required so as to place checks programmatically. Do these steps for all targets and simply exchange identifier. On this picture we used ā€œDevā€. For Manufacturing goal we are going to use ā€œProdā€.

Steps to add macro for target

5. Go to energetic schemes, subsequent to play and cease button. Attempt to choose a scheme and click on on new scheme. A pop up will seem. Choose Manufacturing goal and identify scheme as similar identify i.e. Manufacturing.

Adding new scheme for new target

Programmatically including checks for various targets

Open ViewController.swift and add beneath code

      
        #if Dev
         print("We're utilizing dev model")
        #else
         print("We're utilizing manufacturing goal")
        #endif

Right here we use the flags set by us in construct setting of the goal. For default goal we set flag as ā€œ-D Devā€. Thus right here compiler will test for swift flags for targets. When you have greater than two targets then you possibly can as

        #if Dev
         print("We're utilizing dev model")
        #elseif Staging
         print("We're utilizing staging model")
        #else
         print("We're utilizing manufacturing goal")
        #endif

The place to go from right here

On this put up, we realized that how we are able to add a number of targets to swift undertaking. By including a number of targets developer cab be relieved from ache of commenting uncommenting codes associated to completely different app variations.

The post Add a number of targets to swift undertaking – iOSTutorialJunction appeared first on Tech TeTo.

]]>
https://techteto.com/add-a-number-of-targets-to-swift-undertaking-iostutorialjunction/feed/ 0 2414
Rewriting SpeakerClock in SwiftUI | Cocoanetics https://techteto.com/rewriting-speakerclock-in-swiftui-cocoanetics/ https://techteto.com/rewriting-speakerclock-in-swiftui-cocoanetics/#respond Fri, 26 Nov 2021 08:57:25 +0000 https://techteto.com/rewriting-speakerclock-in-swiftui-cocoanetics/ After I began out growing iOS apps, 11 years in the past I put a number of apps on the App Retailer. Since they grew to become fewer and fewer because the revenue from them didn’t warrant updating them. Amongst these my most profitable one was iWoman, which I offered in 2015. My second-most-valuable (by […]

The post Rewriting SpeakerClock in SwiftUI | Cocoanetics appeared first on Tech TeTo.

]]>

After I began out growing iOS apps, 11 years in the past I put a number of apps on the App Retailer. Since they grew to become fewer and fewer because the revenue from them didn’t warrant updating them. Amongst these my most profitable one was iWoman, which I offered in 2015. My second-most-valuable (by way of income) remained my beloved SpeakerClock, the final app standing.

I had left SpeakerClock on-line for the primary motive that it stored producing like a mean of $100 per 30 days, even with out me doing something on it. For that motive, I didn’t wish to make it free, however fairly put it to a comparatively excessive price ticket of $5. There may be additionally an In-App-Buy of one other $5. I figured ā€œwhy kill the cow whereas it nonetheless produces some tasty milkā€.

The opposite facet impact of those value tags was that – I consider – solely individuals who actually needed what the app was providing would truly buy it. My philosophy with this talking timer was to have the largest LED digits potential, with the performance that helps the talking model of TED Talks, which traditionally have defaulted to a most size of 18 minutes.

Some crashes launched by new iOS variations triggered me to do small bug fixing releases (for iOS 3 in 2010, iOS 5 in 2011, and 2017 for iOS 10). Additionally, wanting again on the launch notes of these variations, I had made this actual promise:

ā€œWe have now completely modernised the code base in order that we will convey you some thrilling new options within the subsequent main launchā€

However I didn’t lie with this assertion, a ā€œsubsequent mainā€ launch would have been model 2.0. However I didn’t ever dare to show the model quantity up that prime. I solely elevated the third digit of the model quantity.

Apple did drive me to do a brand new construct ultimately, once they cracked down on apps which weren’t up to date in too lengthy a time. And the latest replace they did themselves, when the Apple certificates had expired and so they re-signed my app on their servers with out me doing something.

Enter SwiftUI

Over the previous couple of months, I’ve grown very keen on SwiftUI. Being a developer on Apple platforms for greater than a decade made me fairly bored with having to maintain writing the identical MVC code numerous occasions. And that may solely get you want normal performance, nothing actually thrilling. So I jumped on the probability when certainly one of my shoppers requested me to implement a brand new iOS Widget in SwiftUI, within the fall of 2020. Apple had turned to SwiftUI as the one method you would create such widgets due to SwiftUIs skill to provide and protect a static view hierarchy which the system may present to the consumer at sure factors in a timeline with out substantial energy utilization.

My shopper was blissful concerning the outcome and so I used to be tasked with the subsequent stage of SwiftUI improvement. I wanted to implement a watchOS app, additionally solely in SwiftUI. Growth was fairly just like the widget, however this time I additionally wanted to cope with consumer interplay and communication with the iOS counterpart app. That each one took some a number of months greater than the widget, however once more elevated my SwiftUI expertise tremendously.

After having delivered the watch app, I had slightly additional time accessible to do one thing for myself. I do have another concepts for apps, however my ideas turned to SpeakerClock. I figured that this extremely customized UI would lend itself properly to be carried out in SwiftUI.

Paths in Shapes

Crucial asset within the legacy code was the drawing of the massive crimson LED digits and the way they prepare themselves in portrait versus panorama, in a pleasant animation. So my first SwiftUI view was one which had a Path component with the SwiftUI instructions including the trail parts to make up the person bars of the LED. My first error right here involved utilizing a GeometryReader to find out the size of the trail. The LED digits have a set side ratio and the drawing coordinates are primarily based on these.

struct LEDDigit: View
{
   var digit: Int? = nil
    
   var physique: some View
   {
      GeometryReader { proxy in
         let (w, h) = proxy.unitSize

         // high horizontal line
         Path { path in
            path.transfer(to: CGPoint(x: 24 * w, y: 7 * h))
            path.addLine(to: CGPoint(x: 60 * w, y: 7 * h))
            path.addLine(to: CGPoint(x: 62 * w, y: 10 * h))
            path.addLine(to: CGPoint(x: 57 * w, y: 15 * h))
            path.addLine(to: CGPoint(x: 24 * w, y: 15 * h))
            path.addLine(to: CGPoint(x: 21 * w, y: 10 * h))
            path.closeSubpath()
         }
         .activeLEDEffect(when: [0, 2, 3, 5, 7, 8, 9].accommodates(digit))
         ...
}

Whereas this produces the right output, it causes the person Paths to animate individually when rotating the system. I solved this downside by transferring the person path’s code right into a Form the place I’m including the bars solely primarily based on whether or not I’m in search of the energetic or inactive LED parts. The trail(in rect: CGRect) operate arms us the required dimension, so we don’t a GeometryReader any extra.

struct LEDDigitShape: Form
{
   var digit: Int? = nil
   var isActive: Bool
    
   func path(in rect: CGRect) -> Path
   {
      let w = rect.dimension.width / 73
      let h = rect.dimension.peak / 110
        
      var path = Path()
        
      // high horizontal line
        
      if [0, 2, 3, 5, 7, 8, 9].accommodates(digit) == isActive
      {
         path.transfer(to: CGPoint(x: 24 * w, y: 7 * h))
         path.addLine(to: CGPoint(x: 60 * w, y: 7 * h))
         path.addLine(to: CGPoint(x: 62 * w, y: 10 * h))
         path.addLine(to: CGPoint(x: 57 * w, y: 15 * h))
         path.addLine(to: CGPoint(x: 24 * w, y: 15 * h))
         path.addLine(to: CGPoint(x: 21 * w, y: 10 * h))
         path.closeSubpath()
      }
      ...
}

That is used such:

struct LEDDigit: View
{
   var digit: Int? = nil
    
   var physique: some View
   {
   ZStack
   {
      LEDDigitShape(digit: digit, dot: dot, isActive: false)
         .activeLEDEffect(isActive: false)
      LEDDigitShape(digit: digit, dot: dot, isActive: true)
         .activeLEDEffect(isActive: true)
   }
}

The 2 members of the ZStack draw all of the inactive LED parts behind the energetic LED parts. It nonetheless wanted to be two Shapes as a result of one form can solely have a single drawing model. The inactive parts are merely stuffed in a grey. The energetic parts are full of crimson and have a crimson glow round them simulating some radiance.

With this strategy a digit is all the time drawn in its entirety which lends itself to easy resizing.

Format and Orientation Woes

The subsequent step was to combination a number of LED digits and lay them out over the display screen with completely different positions for panorama and portrait orientations, with a easy animation while you rotate the system.

I’ve mainly two layouts:

  1. Hour digits, Colon, Minute digits (in a HStack)- in horizontal structure with the outer sides touching the secure space insets
  2. A VStack of Hour digits and Minute digits – in vertical structure

Sounds simple, however my makes an attempt with HStacks and VStacks failed miserably. In the beginning of the rotation animation the digits would all the time get a really small body increasing into the ultimate one.

I can solely think about that by some means the SwiftUI structure system doesn’t do not forget that these are the identical views. So I attempted giving them static identifiers and I additionally tried geometry matching. However I couldn’t shake these animation artefacts. There have to be some piece lacking in my understanding about view identification.

In the long run I got here again to doing my very own structure inside a GeometryReader, setting body’s width/peak and acceptable offsets (i.e. translation) for particular person parts. This works very properly and likewise lets me have a separate animation for the opacity of the colon.

The colon sticks to the correct facet of the hour digits and disappears in portrait structure. By sorting view modifiers in a sure method I used to be capable of get this impact that the colon fades in with a slight delay.

var physique: some View
{
   GeometryReader { proxy in
            
   let digitSize = self.digitSize(proxy: proxy)
   let colonSize = self.colonSize(proxy: proxy)
   let centeringOffset = self.centeringOffset(proxy: proxy)
   let isLandscape = proxy.isLandscape
            
   let timerSize = self.timerSize(proxy: proxy)
            
   Group
   {
      LEDNumber(worth: mannequin.countdown.minutes)
      .body(width: digitSize.width * 2, peak: digitSize.peak)
      .animation(nil)
                
      LEDColon()
      .body(width: colonSize.width, peak: colonSize.peak)
      .offset(x: digitSize.width * 2, y: 0)
      .animation(nil)
      .opacity(isLandscape ? 1 : 0)
      .animation(isPadOrPhone ? (isLandscape ? .easeInOut.delay(0.2) 
                              : .easeInOut) : nil)
                
      LEDNumber(worth: mannequin.countdown.seconds)
      .body(width: digitSize.width * 2, peak: digitSize.peak)
      .offset(x: isLandscape ? digitSize.width * 2 + colonSize.width : 0,
              y: isLandscape ? 0 : digitSize.peak)
      .animation(nil)
   }
   .offset(x: centeringOffset.width,
           y: centeringOffset.peak)

You’ll be able to see that I’m particularly disabling animation with .animation(nil) for probably the most components as a result of I discovered that the animation in any other case is all the time out of sync with the rotation resizing animation. The LED colon alternatively has its personal animation with an extra delay of 0.2 seconds.

The second motive why I explicitly disabled animations is as a result of on the Mac model these animations would lag behind the resizing of the app’s window. This resizing additionally switches between each layouts relying on the way you drag the window nook, type of like ā€œresponsive designā€ as we now have seen on HTML internet pages. Extra on Mac issues additional down beneath.

Multi-Modal Buttons

One other problem that had me strive a number of approaches involved the preset buttons (high left) and site visitors gentle buttons (middle backside). These buttons have a unique operate for a single faucet (choose) versus a protracted press (set).

The principle downside is that you just can’t have a easy .onLongPressGesture as a result of this prevents the conventional faucets from being dealt with. One strategy is to have a .simultaneousGesture for the lengthy press, however then the faucet motion is executed proper (i.e. ā€œsimultaneousā€) after the lengthy press motion for those who carry the finger over the button. The opposite strategy is to make use of a .highPriorityGesture which once more disables the built-in faucet.

I ended up with the next strategy which makes use of the gesture masks to selectively disable the lengthy press gesture if there isn’t a lengthy press motion and to disable the faucet gesture if a protracted press was detected.

struct LEDButton<Content material: View>: View
{
   var motion: ()->()
   var longPressAction: (()->())?
   @ViewBuilder var content material: ()->Content material
    
   @State fileprivate var didLongPress = false
    
   var physique: some View
   {
      Button(motion: {}, label: content material)  // should have empty motion
      .contentShape(Circle())
      .buttonStyle(PlainButtonStyle())   // wanted for Mac
      .simultaneousGesture(LongPressGesture().onEnded({ _ in
         didLongPress = true
         longPressAction!()
         didLongPress = false
      }), together with: longPressAction != nil ? .all : .subviews)
      .highPriorityGesture(TapGesture().onEnded({ _ in
         motion()
      }), together with: didLongPress ? .subviews : .all)
   }
}

This strategy makes use of a customized TapGesture in tandem with the LongPressGesture. A @State variable retains monitor of the lengthy press. We do have to reset didLongPress to false or else all subsequent faucets would proceed to be ignored. I discovered that I don’t want a dispatch async for placing it again to false.

I consider that the explanation for that’s that the primary setting of the variable causes the physique to be up to date and thus the together with: to disable the faucet gesture whereas in progress. Thus the faucet doesn’t hearth upon releasing the lengthy press. Good to know: The .all allows the gesture and the .subviews disables a gesture.

Opposite to different approaches I’ve seen on the web this strategy preserves the usual habits of Button for highlighting, When you press a customized button like this, it makes it barely clear.

A Mac Model – For Free?

The large promise of SwiftUI is that you’d get a Mac model of your app for little additional work, successfully ā€œtotally freeā€. So I made a decision to place this to the take a look at additionally produce a macOS model. I set the focused gadgets to iPhone, iPad, Mac and selected the ā€œOptimize Interface for Macā€ as a result of that sounded to me like the higher outcome.

This optimized mode triggered some points for my customized buttons, as a result of they received changed with empty spherical rects destroying my customized look. You’ll be able to forestall this modification by including .buttonStyle(PlainButtonStyle()).

Aside from this my code actually did run as a local Mac app fairly properly. Behind the scenes although it’s all Mac Catalyst. As I perceive it, which means UIKit remains to be on the helm, on Mac only a macOS model of it.

I left the code signing settings alone as I needed to have customers be capable to set up the Mac and iOS variations with the identical buy. This ā€œcommon buyā€ is enabled by having the identical bundle identifier for each variations.

Some very minor tweaks had been required for adjusting some minimal and most button sizes. There’s a bug on macOS that stumped me for some time. Solely on Mac I discovered that after I tapped in sure spots in my app this could trigger gestures to cease working. Then after I triggered a brand new structure by resizing the window, all the pieces returned again to regular.

My workaround for this was to connect the Pan Gesture (for setting the timer) solely to the LED digits. This manner there isn’t a interference and all buttons proceed to work usually. The system may get confused by having too many conflicting gestures on high of one another.

A side-effect of the Mac model is that you just begin to connect keyboard shortcuts to buttons. This was additionally a motive why I needed to get Button to work with faucet and lengthy press versus making a customized view that isn’t a button.

let title = "(index+1)"

PresetButton()
.keyboardShortcut(KeyEquivalent(title.first!), modifiers: [.command])

This manner you may set off the preset buttons additionally with COMMAND plus quantity. And never only for the Mac app, however that works for iPads with connected keyboard as properly.

That received me considering, that perhaps it could be nice to permit the house bar to cease/begin the timer, like we’re used to from video gamers. For that goal I’ve an empty fully black button behind the LED digits:

Button(motion: { mannequin.isTimerActive.toggle() },
       label: {
          Rectangle()
          .foregroundColor(.black)
          .body(width: timerSize.width, peak: timerSize.peak)
          .onTapGesture(rely: 2) { mannequin.restoreGreenTime() }
       })
.keyboardShortcut(.house, modifiers: [])
.buttonStyle(PlainButtonStyle())

This button permits me so as to add a keyboard shortcut for house to behave the identical as a faucet. Curiously having a two-tap gesture connected to the Rectangle() poses no downside.

I submitted the Mac construct proper after the one for iOS however initially received a stunning rejection:

The consumer interface of your app will not be in line with theĀ macOS Human Interface Tips. Particularly:

We discovered that the app accommodates iOS contact management directions resembling faucet and swipe.

The explanation for that was that I put again the assistance display screen with a textual content I had beforehand written with iOS in thoughts. I wanted to interchange mentions of swiping with dragging and as an alternative of tapping you’re clicking. I’ve exhausting coded the textual content and formatting for now and with and #if I can change the textual content between a model for Mac and one for iOS.

Group
{
   Textual content("Setting the Timer")
   .font(.headline)
   .padding(.backside, 5)
                        
#if targetEnvironment(macCatalyst)
   Textual content("To regulate the timer, click on on the LED digits and drag horizontally.")
   .font(.physique)
   .padding(.backside, 5)
#else
   Textual content("To regulate the timer swipe left and proper.")
   .font(.physique)
   .padding(.backside, 5)
#endif                 
}

As soon as I had made these adjustments the Mac app was authorized in a short time.

Conclusion

I’ve skilled first hand how I can rewrite an app in SwiftUI and the good pleasure that may be had from deleting all of your crufty Goal-C code when doing so.

SwiftUI is my new love and this manner my app is not a ā€œyoungster from one other momā€. This restores some enthusiasm in me to truly lastly actually add some long-promised ā€œthrilling new optionsā€. For starters I’m considering of getting a watchOS companion app which reveals the timer and permits you to distant management it. One other concept could be to retailer my presets on iCloud in order that they’re the identical on all my gadgets.

I’d love to listen to from you what you consider the method of re-implementing components of apps and even complete apps in SwiftUI.



Additionally printed on Medium.


Tagged as:

Classes: Updates

The post Rewriting SpeakerClock in SwiftUI | Cocoanetics appeared first on Tech TeTo.

]]>
https://techteto.com/rewriting-speakerclock-in-swiftui-cocoanetics/feed/ 0 2366