3D Touch: Electronic scale app and quick action

Source: Internet
Author: User
Tags home screen taptic engine

With the advent of iphone6s and 6s Plus, Apple has shown us a new way to interact: press the gesture again. As you may know, this feature has been launched on Apple Watch and MacBook, but then force Touch is literally meant to add a new dimension to the user's interaction.

If you're curious about why the iphone's force Touch is being renamed 3D Touch, let me tell you that you're not alone (note: please sing it with MJ's tone ...) )。 Not long ago, Craig Federighi, who had previously struggled with the name, described the new feature, which was created by the first micro-blog. Don't know what's wrong with Force Touch because there are too many Star Wars stems? (Translator Note: Actually I do not know this stalk ... )

However, Force Touch and 3d Touch are really different! Force Touch only recognizes the re-press. 3D Touch is much more sensitive in this area, and it can recognize the force of the press.

While this difference may seem trivial, it allows developers to develop more accurate metering apps. For example , this app, called Gravity, uses Force Touch to make your iphone an electronic scale. Although the app was rejected by Apple, it's a great idea. So, to show the workflow of 3D touch, let's make a simple app.

Go ahead and download the initial case. There is only one empty single View in the initial case. I created the necessary UI elements ( UILabel and UIImage ViewController.swift ) in the app, and associated them.

The app is designed to be simple: there are two labels on the Viewcontroller: a title and a text that displays the percentage of compressions.

That... Start writing code! On iphone6s and 6s Plus UITouch , objects have more than CGFloat two types force of attributes, respectively, and maximumPossibleForce . force represents a value that is based on a multiplicity that 1.0 represents the general state. maximumPossibleForce represents the maximum pressure value to withstand.

In any case, when the user touches the screen,touchesBeganmethod is called, and then it istouchesMoved(if the user's finger is sliding on the screen,touchedCancelledAndtouchesEndedwill also be called). In this app, we just need to focus ontouchesMovedMethod.touchesMovedThere are two parameters:touchesAndeventtouchesIt's a pack.UITouchObject thatNSSetThe collection of types (the collection is unordered and has no duplicates). We have to make sure that thetouchesOnly one ofUITouchobjects, but there is also a time to consider incomplete, so it is strongly recommended that you first use optional bindings to determinetouches.firsttouchesThe first one inUITouchObject) is empty. InViewController.swift, add the following code:

override func touchesMoved(touches: Set, withEvent event: UIEvent?) { if let touch = touches.first { if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == UIForceTouchCapability.Available { // 3D Touch capable } } }}

In this if judgment, you also need to add code that determines whether the current device supports 3D touch. If you're just playing, there's no need to verify. However, if the app is to be listed, it must be judged, after all, like iPhone6 these old devices do not support 3D Touch.

In addition, I also used #available the statement (Swift 2.0) to determine whether the current system is ios9+. (If you want to learn more about Swift 2.0, I would recommend that you read this article.) Similarly, if your compilation environment is ios9.0+, then this judgment can be omitted.

Want to get the percentage of compressions? That's too force easy, just divide maximumPossibleForce The attribute by the number of attributes maximumPossibleForce (for touch.maximumPossibleForce Example:) to indicate the maximum pressure value that can be sustained. Then, update the text:

 override func touchesmoved (touches:set, withevent event: Uievent?) {if let touch = touches.first {if Span class= "Hljs-meta" > #available (IOS 9.0, *) {if traitcollection.forcetouchcapability = = uiforcetouchcapability.available {//3D Touch capable let force = Touch.force/touch.maximumpossibleforce Forcelabel.text =  "\ [Force]% force"}}}}
                              

If you run this program on iphone6s/6s Plus, you can see the pressure percentage when you press the screen. But in fact we want to know the weight of the object on the iphone, not the percentage. According to Ryan McLeod's app, the maximum value of the sensor's metering range is 385g. Therefore, maximumPossibleForce It is equivalent to 385g (equivalent to 3.8N). With a simple calculation, the pressure percentage can be converted to grams. The only thing that needs to be done is to use a percentage *385. For objects heavier than 385g, change the label to a text similar to "385+ grams".

To this, touchesMoved The code in the method is updated to:

Override Func touchesmoved (touches:Set, WitheventEvent:uievent?) {if let touch = touches. First { if #available (IOS 9.0, *) { if traitcollection.forcetouchcapability = = Uiforcetouchcapabili Ty. Available { if touch.  Force >= Touch.maximumpossibleforce {Forcelabel.  Text = "385+ grams"} else {let force = touch.  Force/touch.maximumpossibleforce let grams = Force * 385 Let roundgrams = Int (grams) forcelabel.  Text = "\ (roundgrams) grams"             }}}}} 

And then... You have an e-scale app ...

There is also a small problem: when the object or touch event ends, the text is not reset. You can implement the touchesEnded method to achieve the effect:

override func touchesEnded(touches: Set, withEvent event: UIEvent?) { forceLabel.text = "0 gram"}
Quick actions on the home screen

Another use of 3D touch is the quick action on the home screen. Quick actions allow users to jump directly from a shortcut to somewhere in the app. Pressing the app icon shortcut will appear. When it comes to 3D touch, apps like Twitter and Instagram showcase this new feature.

Let's add a quick action to the scale app (change the white background to blue). To add a info.plist shortcut, first open the project catalog (click on the project name in the navigation bar and find the tab in the TARTGET info ). In this file, add UIApplicationShortcutItems an array. The elements in the array are dictionaries that contain a quick-action configuration:

  • UIApplicationShortcutItemType (required): A unique identifier for the shortcut action (string type). It is recommended that you prefix the bundle ID or other unique string as an identifier.
  • UIApplicationShortcutItemTitle(required): equivalent to the shortcut action of the title (string type), the user can see. For example, "Show recent photos" text.
  • UIApplicationShortcutItemSubtitle(optional): The subtitle of the shortcut operation (string type). For example, "photos taken yesterday." If you want to add an icon to a shortcut, you can customize it or use the system's own.
  • UIApplicationShortcutItemIconType(optional): Indicates which system icon you want to select as the icon for the shortcut action (string type).
  • UIApplicationShortcutItemIconFile(optional): Indicates that a custom icon (string type) is added to the shortcut action.
  • UIApplicationShortcutItemUserInfo(optional): Extra information passed when the shortcut is interacting (translator Note: UserInfo parameter similar to notification) (Dictionary type).

In this array, we will add 4 configurations to the custom shortcut action. Then, your info.plist file should look like this:

  Note that I used the  $ (Product_bundle_ IDENTIFIER)     com.appcoda.scale     g    Span style= "color: #008000;" >eneral     i    nfo.plist    $ (product_bundle_identifier)    

The last thing to do is to implement the process of user-triggered quick action. Shortcuts need to AppDelegate.swift be performActionForShortcutItem handled in the method. This method is called when the shortcut is used to start the operation. So, implement this method and handle the shortcut operation in the method:

(Bool) -> Void) {    // Handle quick actions    completionHandler(handleQuickAction(shortcutItem))}

This method needs to completionHandler be called and passed in a Boolean value, depending on whether the shortcut operation succeeds or not. Here we encapsulate a handleQuickAction method to handle the shortcut. If you have more than one shortcut, the best way to do UIApplicationShortcutItemType This is to rawValue use an enumeration as an enumeration (note: You can refer to this article if you are unfamiliar with enumerations). Define an enumeration and implement handleQuickAction the method in which the background color is modified to blue.

Enum Shortcut:string {Case Openblue ="Openblue"}FuncHandlequickaction (Shortcutitem:uiapplicationshortcutitem), Bool {var quickactionhandled = false let type = shortcutItem.type.componentsSeparatedByString ("."). last! if let shortcuttype = Shortcut.init (rawvalue:type) { switch shortcuttype {case . OpenBlue:self.window?. BackgroundColor = Uicolor (red: 151.0/255.0, green: 187.0/255.0 , Blue: 255.0/255.0, Alpha: c14>1.0) quickactionhandled = True}} return quickactionhandled}      

Everything is so simple. Now run the program and use the quick action to start the app, you can see the background is already blue.

There's one more thing.

There's one more question you can't forget ... In terms of program startup sequence, it is different to start a program and wake up with a quick action. As we all know, program startup calls willFinishLaunchingWithOptions and didFinishLaunchingWithOptions methods. However, when the shortcut is used to wake up, performActionForShortcutItem Only the method is triggered (translator Note: This means that using the shortcut action to start will walk three methods, while using the quick action wake up only go one, specific method list such as).

If you look back didFinishLaunchingWithOptions at the method, you will find inside I wrote a line setting the background color to white code. This is used when you start the program directly.

UIApplication, didFinishLaunchingWithOptions launchOptions:    [NSObject: AnyObject]?) -> Bool {    // Override point for customization after application launch.    self.window?.backgroundColor = UIColor.whiteColor() return true}

The problem is: when you willFinish wake up the program with a quick action, the didFinish and performActionForShortcutItem will be called. So the background color is set to white first, and then it is set to blue. Obviously you don't want the background color to be set to white when you start with a quick action.

To solve this problem, we need didFinishLaunchingWithOptions to add conditional judgment to the implementation of the method:

Func Application (Application:UIApplication, didfinishlaunchingwithoptions launchoptions: [Nsobject:anyobject]?) -Bool {print ( "didfinishlaunchingwithoptions called") var islaunchedfromquickaction = false //Check if it ' s launched from Quick Action i F Let Shortcutitem = launchoptions? [uiapplicationlaunchoptionsshortcutitemkey] as? uiapplicationshortcutitem {islaunchedfromquickaction =  True //Handle the Sortcutitem handlequickaction (Shortcutitem)} else {self.window?. BackgroundColor = uicolor.whitecolor ()} //Return False if the App is launched from a shortcut, so performaction ... won't be called. return!islaunchedfromquickaction}         

By judging the optional value of UIApplicationLaunchOptionsShortcutItemKey whether the user is started by a quick action. UIApplicationShortcutItem The type that can be used as an optional value. If the program is started by a quick action, we can call handleQuickAction the method directly to change the background color to blue.

Because we have didFinishLaunchingWithOption handleQuickAction called it in the method, it is not necessary to performActionForShortcutItem call it again in the method. So finally we return one false , telling the system not to call performActionForShortcutItem the method again.

Run the program again! Perfect!

At last

3D Touch is a great way to add another way of interacting with your program. But don't forget that not all devices support 3D Touch at this time.

Through this article, you should be able to add quick actions to your app, but also to measure the intensity of the press.

By the way, you can download the final version of the program here. Similarly, please leave a message.

My opinion on "translating" 3D touch

Hey, now with the iphone and IOS9, which supports 3D touch, is a great technology masterpiece. Let's see what this brings to both the developer and the user. The text is primarily my understanding of 3D touch, and then lists some points to note.

Wrong foot

Originally I wanted to write a reading about 3D touch, but a question--xcode7 simulator does not simulate 3D touch.

Apple's official statement is:

In Xcode7.0, you must develop with a real machine that supports 3D touch. Because the Xcode7.0 simulator does not support 3D Touch.

It's a sad story, but what's the way? I think Apple should try to simulate it. It may be visible in the next Xcode release version.

Another problem is that the new iphone has not yet been released in Poland and may have to wait 2 weeks (note: The author wrote the article before the Polish iphone was released).

There's another way, I'm going to be in San Francisco and Palo Alto for a whole January, so I might buy an iphone, but I'm not sure if it's 6s or 6s Plus.

If you buy a device, it will definitely release a big wave of 3D touch articles.

Peek and pop operations

This is the first feature of Apple's introduction to 3D touch--or two features.

    • The light pressure (peek, lightly pressed) operation allows the user to preview the content without leaving the current interface. If you tap an option to bring up a small rectangular view, it supports a light pressure operation.
    • Peek gesture pop-up view should be large enough so that the content will not be blocked by the finger, so that the user can choose whether the pressure, that is, pop operation (Translator note: Peek operation is a tap, for previewing, pop operation is the pressure, for further confirmation. Pop can meet the need to enter a specific page after the preview.
    • Pop is when the user in the Peek pop-up view to increase the intensity of the press, display more detailed content.
    • Even if peek can give the user enough information, you should also let the user turn the operation into a pop. The interface displayed by the pop should be the same as the user clicks into the interface.
    • Do not put the button in Peek Preview interface, because the user's finger left the preview interface, the preview screen disappears, so there is no point to the button.
    • When the user slides up in the preview screen, Peek can provide some quick actions (quick action). You can add some shortcuts to the preview screen so that the user can slide up and choose the action you've provided.
    • If you provide a long press gesture event for an option (touch-and-hold, or long presses), you can use peek instead of a long-press gesture, which is a good attempt.
    • If you want to use quick action, peek, and pop, remember to determine if 3D touch is available before you use it.
    • Not every device supports peek and pop operations, and 3D touch may also be disabled. So do not allow certain events to be triggered by peek only. It is best to have an alternative, that is, the view can also be displayed by a long press gesture.
Quick action

Next, let's describe some of the quick actions that some users have when they apply the icon to stress.

    • The pop-up box contains the main title, subtitle, and icon.
    • This action can display the update information when the application is updated.
    • Your app should provide at least one quick option in the home screen. This allows users to use gestures to manipulate your app, quickly and easily.
    • Medical use can provide up to four quick actions.
    • Do not use shortcut actions to alert users to updates, changes, and so on. Notifications (notifications) are more capable of these tasks if necessary.
    • The naming of shortcuts should be concise, and if necessary, there should be subtitles and icons. Try to make the user clear about the action. If a subtitle is provided, the title bar will be longer, and if the size does not fit, the system will automatically intercept it. If there is no subtitle, the main title will be wrapped for a long time.
At last

3D Touch is a very cool feature that provides a whole new way of interacting. The device contains a linear vibrator (taptic Engine), so the device responds when you press the screen--that's great, and I can't wait to try.

Unfortunately, Apple didn't solve the problem that can't be simulated in the latest Xcode 7 Beta 2, or do you want them to get it done-maybe they don't fix it to increase sales, because users can't wait to try this new feature, and the simplest and most brutal way is to buy a new device:D.

I can't wait to try out apps based on 3D touch, like games and graphics, and some apps I can't imagine. It may also be possible to see the application of weight measurement, such as the weight of a fruit, or the weight of an object placed on the screen, etc.:>.

3D Touch: Electronic scale app and quick action

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.