Animation delay on left side of screen in iOS keyboard extension - swift

I'm working on a keyboard extension for iOS. However, I'm having some weird issues with animations / layers not appearing instantly on the far left of the screen. I use layers / animations to show a "tool tip" when the user presses a key. For all keys except A and Q the tool tips are displayed instantly, but for these two keys there seems to be a slight delay before the layer and animation appears. This only happens on touch down, if I slide into the Q or A hit area the tool tips gets rendered instantly. My debugging shows that the code executes exactly the same for all keys, but for these two keys it has no immediate effect.
Any ideas on if there's anything special with the left edge of the screen that might cause this behaviour? Or am I doing something stupid that might be the cause of this?
This is part of my touch handling code that triggers the tool tip rendering:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if(!shouldIgnoreTouches()) {
for touch in touches {
let location = (touch ).locationInView(self.inputView)
// pass coordinates to offset service to find candidate keys
let keyArray = keyOffsetService.getKeys(_keyboardLayout!, location: location)
let primaryKey = keyArray[0]
if primaryKey.alphaNumericKey != nil {
let layers = findLayers(touch )
if layers.keyLayer != nil {
graphicsService.animateKeyDown(layers.keyLayer as! CATextLayer, shieldLayer: layers.shieldLayer)
_shieldsUp.append((textLayer:layers.keyLayer, shieldLayer:layers.shieldLayer))
}
}
}
}
}
animation code:
func animateKeyDown(layer:CATextLayer, shieldLayer:CALayer?) {
if let sLayer = shieldLayer {
keyDownShields(layer, shieldLayer: sLayer)
CATransaction.begin()
CATransaction.setDisableActions(true)
let fontSizeAnim = CABasicAnimation(keyPath: "fontSize")
fontSizeAnim.removedOnCompletion = true
fontSizeAnim.fromValue = layer.fontSize
fontSizeAnim.toValue = layer.fontSize * 0.9
layer.fontSize = layer.fontSize * 0.9
let animation = CABasicAnimation(keyPath: "opacity")
animation.removedOnCompletion = true
animation.fromValue = layer.opacity
animation.toValue = 0.3
layer.opacity = 0.3
let animGroup = CAAnimationGroup()
animGroup.animations = [fontSizeAnim, animation]
animGroup.duration = 0.01
layer.addAnimation(animGroup, forKey: "down")
CATransaction.commit()
}
}
unhide tooltip layer:
private func keyDownShields(layer:CATextLayer, shieldLayer:CALayer) {
shieldLayer.hidden = false
shieldLayer.setValue(true, forKey: "isUp")
shieldLayer.zPosition = 1
shieldLayer.removeAllAnimations()
layer.setValue(true, forKey: "isUp")
}

This is caused by a feature in iOS 9 which allows the user to switch apps by force pressing the left edge of the screen while swiping right.
You can turn this off by disabling 3D touch but this is hardly a solution.
I am not aware of any API that allows you to override this behavior.

The official solution is overriding preferredScreenEdgesDeferringSystemGestures of your UIInputViewController.
https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys
However, it doesn't seem to work on iOS 13 at least. As far as I understand, that happens due to preferredScreenEdgesDeferringSystemGestures not working properly when overridden inside UIInputViewController, at least on iOS 13.
When you override this property in a regular view controller, it works as expected:
override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
return [.left, .bottom, .right]
}
That' not the case for UIInputViewController, though.
UPD: It appears, gesture recognizers will still get .began state update, without the delay. So, instead of following the rather messy solution below, you can add a custom gesture recognizer to handle touch events.
You can quickly test this adding UILongPressGestureRecognizer with minimumPressDuration = 0 to your control view.
Another solution:
My original workaround was calling touch down effects inside hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?, which is called even when the touches are delayed for the view.
You have to ignore the "real" touch down event, when it fires about 0.4s later or simultaneously with touch up inside event. Also, it's probably better to apply this hack only in case the tested point is inside ~20pt lateral margins.
So for example, for a view with equal to screen width, the implementation may look like:
let edgeProtectedZoneWidth: CGFloat = 20
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
guard result == self else {
return result
}
if point.x < edgeProtectedZoneWidth || point.x > bounds.width-edgeProtectedZoneWidth
{
if !alreadyTriggeredFocus {
isHighlighted = true
}
triggerFocus()
}
return result
}
private var alreadyTriggeredFocus: Bool = false
#objc override func triggerFocus() {
guard !alreadyTriggeredFocus else { return }
super.triggerFocus()
alreadyTriggeredFocus = true
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
alreadyTriggeredFocus = false
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
alreadyTriggeredFocus = false
}
...where triggerFocus() is the method you call on touch down event. Alternatively, you may override touchesBegan(_:with:).

Related

Cannot disable, then reenable touch, after an SKAction animation

I am working on an interactive, animated scene. I want all touches on the scene to be disabled on entry. Then, once the objects (which are subclassed nodes) in the scene finish rotating/moving, I want to re-enable all touches on the screen to allow interaction. I have disabled user interaction using this code:
override func didMove(to view: SKView) {
setupNodes()
view?.isUserInteractionEnabled = false
spinLocations()
}
This is the code, within the scene file, for spinLocations:
func spinLocations() {
var allLocationArrays = [[String : CGPoint]]()
var previousArray = hiddenLocationPositions
for _ in 0...SearchConstant.numSpins {
let freshArray = generateNewLocationArray(previous: previousArray)
allLocationArrays.append(freshArray)
previousArray = freshArray
}
for (item, _) in hiddenLocationPositions {
let node = fgNode.childNode(withName: item) as! LocationNode
node.spin(position: allLocationArrays) // this is function below
}
hiddenLocationPositions = previousArray
}
This is the code for the animations in the node class:
func spin(position: [[String : CGPoint]]) {
var allActions = [SKAction]()
for array in position {
let action = SKAction.move(to: array[self.name!]!, duration: 2.0)
allActions.append(action)
}
let allActionsSeq = SKAction.sequence(allActions)
self.run(SKAction.sequence([SKAction.wait(forDuration: 5.0), allActionsSeq, SKAction.run {
self.position = position[position.count - 1][self.name!]!
},]))
}
This is the code for passing back the touches to the main scene from this class:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let parent = self.parent else { return }
}
As you can see, touch is not disabled here.
I do not want to add a "waitForDuration" SKAction to the runBlock to change the view status after the previous action; I want the program to determine when the animations are finished executing and then re-enable touches.
In order to do this, I theorised using a completion handler might work, but it only re-enables touches immediately (e.g. handling a handler to spin causes the touches to be detected again). Previously, I also tried to disable the view in the runBlock, but of course, that is run instantaneously. How do I ensure that the touches are re-detected following the animation without using "waitForDuration."?
So, this is a simple example that shows how you can:
1) Disable touches completely
2) Spin a node
3) When node is done with spinning, to enable touches
Here is the code (you can copy/paste it to try how it works):
class Object:SKSpriteNode{
func spin(times:Int,completion:#escaping ()->()) {
let duration = 3.0
let angle = CGFloat(M_PI) * 2.0
let oneRevolution = SKAction.rotate(byAngle: angle , duration: duration)
let spin = SKAction.repeat(oneRevolution, count: times)
let sequence = SKAction.sequence([spin,SKAction.run(completion)])
run(sequence, withKey:"spinning")
}
}
class WelcomeScene: SKScene {
override func didMove(to view: SKView) {
view.isUserInteractionEnabled = false
print("Touches Disabled")
let object = Object(texture: nil, color: .purple, size: CGSize(width: 200, height: 200))
addChild(object)
object.spin(times: 3, completion: {[weak self] in
self?.view?.isUserInteractionEnabled = true
print("Touches Enabled")
})
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touch detected")
}
deinit {
print("Welcome scene deinited")
}
}
Here, you disable touches when scene is loaded, start spinning the object, and you pass a completion block to it... That block of code is used here:
let sequence = SKAction.sequence([spin,SKAction.run(completion)])
So after spinning, that block will be executed. Now, there are different ways to do this...Personally, I would use delegation, but I thought this can be less confusing... I can write an example for delegation too if needed, but basically, what you would do, is to set a scene as a delegate of your custom node, and notify it about spinning is done, so the scene can tell the view to re-enable the touches.

SpriteKit tracking multiple touches

I have several buttons that move a main character. (Left, right, jump, etc.) But, when I touch more than one button at a time, the previous one is ended. My question is, how do I keep both touches alive for the duration of their touches? As an example, this would allow the character to move forward and jump at the same time. I have set multipleTouchEnabled to true. I've read that using a dictionary to track touches would help, but I can't seem to wrap my head around the implementation.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInView(nil)
if location.x < self.size.width / 2 && location.y > self.size.height / 2 {
movingLeft = true
}
if location.x > self.size.width / 2 && location.y > self.size.height / 2 {
movingRight = true
}
if location.x < self.size.width / 2 && location.y < self.size.height / 2 {
jump()
}
if location.x > self.size.width / 2 && location.y < self.size.height / 2 {
jump()
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
movingLeft = false
movingRight = false
}
func jump() {
mainCharacter.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
mainCharacter.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 400))
}
The logic
You should create a dictionary of active touches.
private var activeTouches = [UITouch:String]()
Every time a touch begins you save it into the dictionary and assign to it a label.
activeTouches[touch] = "left"
So when the touch does end you can search for it into your dictionary and find the related label. Now you know which button has been released by the user.
let button = activeTouches[touch]
if button == "left" { ... }
And don't forget to remove it from the dictionary.
activeTouches[touch] = nil
The implementation
class GameScene: SKScene {
private var activeTouches = [UITouch:String]()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let button = findButtonName(from:touch)
activeTouches[touch] = button
tapBegin(on: button)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
guard let button = activeTouches[touch] else { fatalError("Touch just ended but not found into activeTouches")}
activeTouches[touch] = nil
tapEnd(on: button)
}
}
private func tapBegin(on button: String) {
print("Begin press \(button)")
// your custom logic goes here
}
private func tapEnd(on button:String) {
print("End press \(button)")
// your custom logic goes here
}
private func findButtonName(from touch: UITouch) -> String {
// replace this with your custom logic to detect a button location
let location = touch.locationInView(self.view)
if location.x > self.view?.frame.midX {
return "right"
} else {
return "left"
}
}
}
In the code above you should put your own code into
tapBegin: this method receive the label of a button and start some action.
E.g. start running.
tapEnd: this method receive the label of a button and stop some action.
E.g. stop running.
findButtonName: this method receives a UITouch and returns the label of the button pressed by the user.
Test
I tested the previous code on my iPhone. I performed the following actions.
started pressing the right of the screen
started pressing the left of the screen
removed finger from the right of the screen
removed finger from the left of the screen
As you can see in the following log the code is capable of recognizing different touches
Begin press right
Begin press left
End press right
End press left
Conclusion
I hope I made myself clear. Let me know if something is not.
Issue
For me it was a bit foolish but there's an option that I miss to enable in my storyboard in order to handle multiple touch in my GameScene of type SKScene.
When one of the overwritten functions is being called, you should have more than 1 touch contained in touches.
Those functions are indeed:
touchesBegan
touchesMoved
touchesEnded
touchesCancelled
... and the way to retrieve the touches is indeed to browse through them. However, if you are only able to retrieve one touch only, follow the steps bellow.
Debugging
Here's what you can do to see if you have multiple touches in your set of touches:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for (i, t) in touches.enumerated() {
print(i, t.location(in: self))
self.touchMoved(toPoint: t.location(in: self))
}
}
Output:
There you should find a 0 for the first touch and a 1 when you touch with 2 fingers... and so on.
Solution
I case you encounter the same problem than me and have only the touch t at index 0 but no other touch, you should see upper in the hierarchy of views if all of them are enabled for multi-touch. In my case it was the view containing the GameScene of type SKScene that did not have the option Multiple Touch enabled. See below:

SpriteKit Scale on tap

im trying to create a "button touch" effect for one of my sprites, it works well but then I tap with 2 or more fingers at the same time, i get really weird results, here is my code:
let buttonPressAction = SKAction.scaleBy(0.8, duration: 0)
var button = SKNode()
override func didMoveToView(view: SKView) {
//assign sprite to node
button = self.childNodeWithName("button") as! SKSpriteNode!
}
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if button.containsPoint(location) {
button.runAction(buttonPressAction)
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
button.runAction(buttonPressAction.reversedAction())
}
Try changing the SK scale action from
...scaleBy
to
...scaleTo
to ensure it will always scale to the same size. With scaleBy it will scale it by 0.8, not to 0.8. That most likely causes the weird results on multiple touches because you are scaling by 0.8 for each finger/tap.
I never used reverseAction before so I am not sure if that might cause issues. If it does just reset the button by scaling it back to 1
...scaleTo(1, duration: 0)
As as side note you can just say
for touch in touches
instead of
for touch: AnyObject in touches

How can I limit the range of motion on a custom UIControl Knob?

I'm following the tutorial here, which demonstrates how to implement a custom UIControl. However, I'd like to stop the custom control from spinning endlessly. I've been able to hinder the ability to spin the knob but have been unable to create a definite stopping point.
My Attempt
In the code below I'm using the authors angle variable which ranges from 0 to 360. The logic is a bit wonky, but I'm
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
super.continueTrackingWithTouch(touch, withEvent: event)
if (angle <= 1) {
angle = 2
return false
} else if angle >= 356 {
angle = 355
return false
} else {
let lastPoint = touch.locationInView(self)
self.moveHandle(lastPoint)
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
return true
}
}
view code on github
note: I've tried all of the obvious operators and logic. I feel like this is the wrong approach entirely.
Result
Basically, the controls motion will stop at 1, but only if I'm moving slowly. If I quickly drag the knob, it'll spin right past the 1, allowing the control to spin endlessly.
Question
How can I properly limit the UIControls range of motion from 1 to 355?
I've put together a simple working project that you can download and test.
project files
Change continueTrackingWithTouch to:
// Part of UIControl, used to track user input
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let lastPoint = touch.locationInView(self)
self.moveHandle(lastPoint)
return super.continueTrackingWithTouch(touch, withEvent: event)
}
Change moveHandle to:
func moveHandle(lastPoint:CGPoint){
let threshholdAngle = 180
let centerPoint:CGPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
let currentAngle:Double = AngleFromNorth(centerPoint, p2: lastPoint, flipped: false)
let angleInt = Int(floor(currentAngle))
let newAngle = Int(360 - angleInt)
if abs(newAngle - angle) > threshholdAngle {
return
}
//Store the new angle
angle = newAngle
sendActionsForControlEvents(UIControlEvents.ValueChanged)
//Update the textfield
//textField!.text = "\(angle)"
//Redraw
setNeedsDisplay()
}

show scratch-card effect with the help of using scratch and win example

I am new in ios developement.i need to show scratch-card effect for an iPhone app after scratches if coupon number is visible i need to show alert message How can i do this?.i have download sample code from iPhone - Scratch and Win Example and also i have done showing below screen and scratches also works fine
if UILabel text is visible i want to show alert message How can i do this?
i have attached screen shot for your refference
i Found very nice Github example please take a look this and impliment as par you need hope this helps to you my Frnd.
CGScratch This is same thing that you want to apply.
review the code and check the visible area of Number else check che scration overImage is tatally removed of not if remove then show Alert.
A simple UIImageView subclass that allows your UIImageView become a scratch card.
In your storyboard or xib set custom class of your UIImageView that represents your scratch image to ScratchCardImageView. Change lineType or lineWidth to change the appearance of the scratch lines.
Download example
Swift 3:
import UIKit
class ScratchCardImageView: UIImageView {
private var lastPoint: CGPoint?
var lineType: CGLineCap = .square
var lineWidth: CGFloat = 20.0
override func awakeFromNib() {
super.awakeFromNib()
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
lastPoint = touch.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, let point = lastPoint else {
return
}
let currentLocation = touch.location(in: self)
eraseBetween(fromPoint: point, currentPoint: currentLocation)
lastPoint = currentLocation
}
func eraseBetween(fromPoint: CGPoint, currentPoint: CGPoint) {
UIGraphicsBeginImageContext(self.frame.size)
image?.draw(in: self.bounds)
let path = CGMutablePath()
path.move(to: fromPoint)
path.addLine(to: currentPoint)
let context = UIGraphicsGetCurrentContext()!
context.setShouldAntialias(true)
context.setLineCap(lineType)
context.setLineWidth(lineWidth)
context.setBlendMode(.clear)
context.addPath(path)
context.strokePath()
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
Updated
With this solution touch events will be tracked only inside the UIImageView bounds. If you need touch events to start already outside your scratchcard, see ScratchCardTouchContainer example
You can also check this github tutorial for scratch:
https://github.com/SebastienThiebaud/STScratchView
https://github.com/moqod/iOS-Scratch-n-See