Using scrollViewDidScroll with multiple UIScrollViews - cocoa

I have two horizontally scrolling UIScrollViews stacked vertically on top of each other within one ViewController. Each UIScrollView takes up half the screen. I am trying to independently track the position of both UIScrollViews.
I have successfully used this to track the position of the top UIScrollView:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1 {
int Position = (scrollView1.contentOffset.x);
if (Position == 0) {
NSLog(#"Play A");
}
else if (Position == 280) {
NSLog(#"Play B");
}
//etc.
}
I would like to track the position of the bottom UIScrollView as well.
When I try to use this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView2 {
int Position2 = (scrollView2.contentOffset.x);
if (Position2 == 0) {
NSLog(#"Play A2");
}
else if (Position == 280) {
NSLog(#"Play B2");
}
//etc.
}
I get an error that says "Redefinition of FirstViewConroller scrollViewDidScroll".
So, determined to press on, I tried a rather hackish solution and attempted to use this instead:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView2
{
int Position2 = (scrollView2.contentOffset.x);
if (Position2 == 0) {
NSLog(#"Play A2");
}
else if (Position2 == 280) {
NSLog(#"Play B2");
}
//etc.
}
The problem with this is that it triggers both methods when I move either of the UIScrollViews. For example -- if I move the bottom UIScrollView 280 pixels (one image) to the right, the output I get in the console is:
PlayB
PlayB2
And if I move the top UIScrollView three images to the right the output I get is:
PlayC
PlayC2
Which doesn't make any sense to me.
I think I may be bumping up against my own incomplete understanding of how delegates work. Within the viewDidLoad method I am setting both:
scrollView1.delegate = self;
scrollView2.delegate = self;
Perhaps this is part of the problem? Maybe I am causing trouble by declaring that both scrollViews have the same delegate? Just not sure.
I've also tried combining all of my conditional statements into one method -- but I only want to track the position of the bottom UIScrollView when it moves and the position of the top UIScrollView when it moves, and putting the logic all in one method reports both positions when either one moves and this is not what I'm looking for.
Any help is appreciated. Would love to solve this particular problem, but would also really love to understand any bigger issues with how I'm approaching this. Still new at this. Keep thinking I'm getting the hang of it and then I run into something that stops me in my tracks..

This is exactly what the UIScrollView parameter is for. Create connections to scrollView1 and scrollView2 in IB and then do this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView1 == scrollView) {
// Do stuff with scrollView1
} else if (scrollView2 == scrollView) {
// Do stuff with scrollView2
}
}

There's no reason why the same object can't be the delegate of several different scrollviews. The reason that -scrollViewDidScroll: passes you the scrollview in question is so that you know which scrollview did scroll.
This is the general pattern for delegate messages.

Related

Squashed Sprite when turning horizontally

Unsquashed Sprite Squashed Sprite
My brother has issues with his sprite squashing whilst moving horizontally. The squashing is permanent after moving. I have found the line that causes the problem but cannot figure out what is causing this issue. When I remove this line the squashing stops however the sprite does not turn. He is following Shaun Spalding's Complete Platformer Tutorial and though I've watched it over I cannot find any issues with the actual code.
/// #description Insert description here
// You can write your code in this editor
// get player input
key_left=keyboard_check(vk_left);
key_right=keyboard_check(vk_right);
key_jump=keyboard_check_pressed(vk_up);
// calculate movement
var move=key_right-key_left;
hsp=move*walksp;
vsp=vsp+grv;
if(place_meeting(x,y+1,o_wall)) and (key_jump)
{
vsp=-7;
}
// horizontal collision
if (place_meeting(x+hsp,y,o_wall))
{
while(!place_meeting(x+sign(hsp),y,o_wall))
{
x=x+sign(hsp);
}
hsp=0;
}
x=x+hsp;
// vertical collision
if (place_meeting(x,y+vsp,o_wall))
{
while(!place_meeting(x,y+sign(vsp),o_wall))
{
y=y+sign(vsp);
}
vsp=0;
}
y=y+vsp;
// animation
if(!place_meeting(x,y+1,o_wall))
{
sprite_index=splayerA;
image_speed=0;
if (sign(vsp) > 0) image_index = 1; else image_index = 0;
}
else
{
image_speed=1;
if (hsp==0)
{
sprite_index=s_player;
}
else
{
sprite_index=splayerR;
}
}
if (hsp != 0) image_xscale = sign(hsp); //this line is wrong and causes the squishing
A possible cause of this is that you've set the image_xscale to a different value before using the line:
if (hsp != 0) image_xscale = sign(hsp);
For example, you may have set this in the Create Event to enlarge the sprite:
image_xscale = 2;
But that value is reset after setting image_xscale again, as that line will only return -1 or 1 because of the Sign().
One quick solution is to apply the scale change to that line of code, like this:
if (hsp != 0) image_xscale = 2 * sign(hsp);
(Once again, presuming you've changed it's scale value somewhere else)
Though another solution is to enlarge the sprite itself in the sprite editor, so the scale doesn't have to be kept in mind everytime.

Xcode UITest scrolling to the bottom of an UITableView

I am writing an UI test case, in which I need to perform an action, and then on the current page, scroll the only UITableView to the bottom to check if specific text shows up inside the last cell in the UITableView.
Right now the only way I can think of is to scroll it using app.tables.cells.element(boundBy: 0).swipeUp(), but if there are too many cells, it doesn't scroll all the way to the bottom. And the number of cells in the UITableView is not always the same, I cannot swipe up more than once because there might be only one cell in the table.
One way you could go about this is by getting the last cell from the tableView. Then, run a while loop that scrolls and checks to see if the cell isHittable between each scroll. Once it's determined that isHittable == true, the element can then be asserted against.
https://developer.apple.com/documentation/xctest/xcuielement/1500561-ishittable
It would look something like this (Swift answer):
In your XCTestCase file, write a query to identify the table. Then, a subsequent query to identify the last cell.
let tableView = app.descendants(matching: .table).firstMatch
guard let lastCell = tableView.cells.allElementsBoundByIndex.last else { return }
Use a while loop to determine whether or not the cell isHittable/is on screen. Note: isHittable relies on the cell's userInteractionEnabled property being set to true
//Add in a count, so that the loop can escape if it's scrolled too many times
let MAX_SCROLLS = 10
var count = 0
while lastCell.isHittable == false && count < MAX_SCROLLS {
apps.swipeUp()
count += 1
}
Check the cell's text using the label property, and compare it against the expected text.
//If there is only one label within the cell
let textInLastCell = lastCell.descendants(matching: .staticText).firstMatch
XCTAssertTrue(textInLastCell.label == "Expected Text" && textInLastCell.isHittable)
Blaines answer lead me to dig a little bit more into this topic and I found a different solution that worked for me:
func testTheTest() {
let app = XCUIApplication()
app.launch()
// Opens a menu in my app which contains the table view
app.buttons["openMenu"].tap()
// Get a handle for the tableView
let listpagetableviewTable = app.tables["myTableView"]
// Get a handle for the not yet existing cell by its content text
let cell = listpagetableviewTable.staticTexts["This text is from the cell"]
// Swipe down until it is visible
while !cell.exists {
app.swipeUp()
}
// Interact with it when visible
cell.tap()
}
One thing I had to do for this in order to work is set isAccessibilityElement to true and also assign accessibilityLabel as a String to the table view so it can be queried by it within the test code.
This might not be best practice but for what I could see in my test it works very well. I don't know how it would work when the cell has no text, one might be able to reference the cell(which is not really directly referenced here) by an image view or something else. It's obviously missing the counter from Blaines answer but I left it out for simplicity reasons.

Xcode 7 ui automation - loop through a tableview/collectionview

I am using xCode 7.1. I would like to automate interaction with all cells from a table/collection view. I would expect it to be something like this:
for i in 0..<tableView.cells.count {
let cell = collectionView.cells.elementBoundByIndex(i)
cell.tap()
backBtn.tap()
}
However this snippet only queries current descendants of the table view, so it will loop through the first m (m < n) loaded cells out of total n cells from the data source.
What is the best way to loop through all cells available in data source? Obviously querying for .Cell descendants is not the right approach.
P.S.: I tried to perform swipe on table view after every tap on cell. However it swipes to far away (scrollByOffset is not available). And again, don't know how to extract total number of cells from data source.
Cheers,
Leonid
So problem here is that you cannot call tap() on a cell that is not visible. SoI wrote a extension on XCUIElement - XCUIElement+UITableViewCell
func makeCellVisibleInWindow(window: XCUIElement, inTableView tableView: XCUIElement) {
var windowMaxY: CGFloat = CGRectGetMaxY(window.frame)
while 1 {
if self.frame.origin.y < 0 {
tableView.swipeDown()
}
else {
if self.frame.origin.y > windowMaxY {
tableView.swipeUp()
}
else {
break
}
}
}
}
Now you can use this method to make you cell visible and than tap on it.
var window: XCUIElement = application.windows.elementBoundByIndex(0)
for i in 0..<tableView.cells.count {
let cell = collectionView.cells.elementBoundByIndex(i)
cell.makeCellVisibleInWindow(window, inTableView: tableView)
cell.tap()
backBtn.tap()
}
let cells = XCUIApplication().tables.cells
for cell in cells.allElementsBoundByIndex {
cell.tap()
cell.backButton.tap()
}
I face the same situation however from my trials, you can do tap() on a cell that is not visible.
However it is not reliable and it fails for an obscur reason.
It looks to me that this is because in some situation the next cell I wanted to scroll to while parsing my table was not loaded.
So here is the trick I used:
before parsing my tables I first tap in the last cell, in my case I type an editable UITextField as all other tap will cause triggering a segue.
This first tap() cause the scroll to the last cell and so the loads of data.
then I check my cells contents
let cells = app.tables.cells
/*
this is a trick,
enter in editing for last cell of the table view so that all the cells are loaded once
avoid the next trick to fail sometime because it can't find a textField
*/
app.tables.children(matching: .cell).element(boundBy: cells.count - 1).children(matching: .textField).element(boundBy: 0).tap()
app.typeText("\r") // exit editing
for cellIdx in 0..<cells.count {
/*
this is a trick
cell may be partially or not visible, so data not loaded in table view.
Taping in it is will make it visible and so do load the data (as well as doing a scroll to the cell)
Here taping in the editable text (the name) as taping elsewhere will cause a segue to the detail view
this is why we just tap return to canel name edidting
*/
app.tables.children(matching: .cell).element(boundBy: cellIdx).children(matching: .textField).element(boundBy: 0).tap()
app.typeText("\r")
// doing my checks
}
At least so far it worked for me, not sure this is 100% working, for instance on very long list.

Windows Phone Gesture Detection

I'm creating a game where the player will use Drag gestures to "slash" an enemy, swiping their finger across the screen to kill them.
I have a feeling this should be easier than it is, but currently the code I have to detect this is:
while (TouchPanel.IsGestureAvailable)
{
GestureSample gs = TouchPanel.ReadGesture();
if (gs.GestureType == GestureType.FreeDrag ||
gs.GestureType == GestureType.HorizontalDrag ||
gs.GestureType == GestureType.VerticalDrag)
{
Current_Start = gs.Position;
Current_End = Current_Start + gs.Delta;
}
if (gs.GestureType == GestureType.DragComplete)
{
DragEnded = true;
}
}
This isn't quite working, though. I need the two vectors of:
Where the drag started
Where the drag ended
What is wrong, and how would I get this to work?
I would try using the onmousedown and onmouseup events to get the start and end points and go from there.

UICollectionView effective drag and drop

I am currently trying to implement the UITableView reordering behavior using UICollectionView.
Let's call a UItableView TV and a UICollectionView CV (to clarify the following explanation)
I am basically trying to reproduce the drag&drop of the TV, but I am not using the edit mode, the cell is ready to be moved as soon as the long press gesture is triggered. It works prefectly, I am using the move method of the CV, everything is fine.
I update the contentOffset property of the CV to handle the scroll when the user is dragging a cell. When a user goes to a particular rect at the top and the bottom, I update the contentOffset and the CV scroll. The problem is when the user stop moving it's finger, the gesture doesn't send any update which makes the scroll stop and start again as soon as the user moves his finger.
This behavior is definitely not natural, I would prefer continu to scroll until the user release the CV as it is the case in the TV. The TV drag&drop experience is awesome and I really want to reproduce the same feeling. Does anyone know how they manage the scroll in TV during reordering ?
I tried using a timer to trigger a scroll action repeatedly as long as the gesture position is in the right spot, the scroll was awful and not very productive (very slow and jumpy).
I also tried using GCD to listen the gesture position in another thread but the result is even worst.
I ran out of idea about that, so if someone has the answer I would marry him!
Here is the implementation of the longPress method:
- (void)handleLongPress:(UILongPressGestureRecognizer *)sender
{
ReorganizableCVCLayout *layout = (ReorganizableCVCLayout *)self.collectionView.collectionViewLayout;
CGPoint gesturePosition = [sender locationInView:self.collectionView];
NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:gesturePosition];
if (sender.state == UIGestureRecognizerStateBegan)
{
layout.selectedItem = selectedIndexPath;
layout.gesturePoint = gesturePosition; // Setting gesturePoint invalidate layout
}
else if (sender.state == UIGestureRecognizerStateChanged)
{
layout.gesturePoint = gesturePosition; // Setting gesturePoint invalidate layout
[self swapCellAtPoint:gesturePosition];
[self manageScrollWithReferencePoint:gesturePosition];
}
else
{
[self.collectionView performBatchUpdates:^
{
layout.selectedItem = nil;
layout.gesturePoint = CGPointZero; // Setting gesturePoint invalidate layout
} completion:^(BOOL completion){[self.collectionView reloadData];}];
}
}
To make the CV scroll, I am using that method:
- (void)manageScrollWithReferencePoint:(CGPoint)gesturePoint
{
ReorganizableCVCLayout *layout = (ReorganizableCVCLayout *)self.collectionView.collectionViewLayout;
CGFloat topScrollLimit = self.collectionView.contentOffset.y+layout.itemSize.height/2+SCROLL_BORDER;
CGFloat bottomScrollLimit = self.collectionView.contentOffset.y+self.collectionView.frame.size.height-layout.itemSize.height/2-SCROLL_BORDER;
CGPoint contentOffset = self.collectionView.contentOffset;
if (gesturePoint.y < topScrollLimit && gesturePoint.y - layout.itemSize.height/2 - SCROLL_BORDER > 0)
contentOffset.y -= SCROLL_STEP;
else if (gesturePoint.y > bottomScrollLimit &&
gesturePoint.y + layout.itemSize.height/2 + SCROLL_BORDER < self.collectionView.contentSize.height)
contentOffset.y += SCROLL_STEP;
[self.collectionView setContentOffset:contentOffset];
}
This might help
https://github.com/lxcid/LXReorderableCollectionViewFlowLayout
This is extends the UICollectionView to allow each of the UICollectionViewCells to be rearranged manually by the user with a long touch (aka touch-and-hold). The user can drag the Cell to any other position in the collection and the other cells will reorder automatically. Thanks go to lxcid for this.
Here is an alternative:
The differences between DraggableCollectionView and LXReorderableCollectionViewFlowLayout are:
The data source is only changed once. This means that while the user is dragging an item the cells are re-positioned without modifying the data source.
It's written in such a way that makes it possible to use with custom layouts.
It uses a CADisplayLink for smooth scrolling and animation.
Animations are canceled less frequently while dragging. It feels more "natural".
The protocol extends UICollectionViewDataSource with methods similar to UITableViewDataSource.
It's a work in progress. Multiple sections are now supported.
To use it with a custom layout see DraggableCollectionViewFlowLayout. Most of the logic exists in LSCollectionViewLayoutHelper. There is also an example in CircleLayoutDemo showing how to make Apple's CircleLayout example from WWDC 2012 work.
As of iOS 9, UICollectionView now supports reordering.
For UICollectionViewControllers, just override collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
For UICollectionViews, you'll have to handle the gestures yourself in addition to implementing the UICollectionViewDataSource method above.
Here's the code from the source:
private var longPressGesture: UILongPressGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongGesture:")
self.collectionView.addGestureRecognizer(longPressGesture)
}
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.Began:
guard let selectedIndexPath = self.collectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
case UIGestureRecognizerState.Changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!))
case UIGestureRecognizerState.Ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
Sources:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/#//apple_ref/doc/uid/TP40012177-CH1-SW67
http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/
If you want to experiment rolling out your own, I just wrote a Swift based tutorial you can look. I tried to build the most basic of cases so as to be easier to follow this.
Here is another approach:
Key difference is that this solution does not require a "ghost" or "dummy" cell to provide the drag and drop functionality. It simply uses the cell itself. Animations are in line with UITableView. It works by adjusting the collection view layout's private datasource while moving around. Once you let go, it will tell your controller that you can commit the change to your own datasource.
I believe it's a bit simpler to work with for most use cases. Still a work in progress, but yet another way to accomplish this. Most should find this pretty easy to incorporate into their own custom UICollectionViewLayouts.

Resources