iOS Autolayout - How to set two different distances between views, depends on the screen height - iphone

I know I'm missing something, because this has to be something easy to achieve.
My problem is that I have in my "loading screen" (the one that appears right after the splash) an UIImageView with two different images for 3.5" and 4" size screen. In a certain place of that images, I put one UIActivityIndicator, to tell the user that the app is loading something in the background. That place is not the same for both images, because one of them is obviously higher that the other, so I want to set an autolayout constraint that allows me to put that activity indicator at different heights, depends on if the app is running in an iPhone 5 or not.
Without Autolayout, I'd set the frame.origin.y of the view to 300 (for example), and then in the viewDidLoad method of the ViewController, I'd ask if the app is running in an iPhone 5, so I'd change the value to, for example, 350. I have no idea how to do this using Autolayout and I think it has to be pretty simple.

You can create an NSLayoutConstraint outlet on your view controller and connect the outlet to the activity indicator's Y constraint in your xib or storyboard. Then, add an updateViewContraints method to your view controller and update the constraint's constant according to the screen size.
Here's an example of updateViewConstraints:
- (void)updateViewConstraints {
[super updateViewConstraints];
self.activityIndicatorYConstraint.constant =
[UIScreen mainScreen].bounds.size.height > 480.0f ? 200 : 100;
}
Of course you will want to put in your appropriate values instead of 200 and 100. You might want to define some named constants. Also, don't forget to call [super updateViewConstraints].

The problem of #Rob answer's is you should do a lot of code for each constraint.
So to resolve that, just add ConstraintLayout class to your code and modify constraint constant value for the device that you want in the IB :
//
// LayoutConstraint.swift
// MyConstraintLayout
//
// Created by Hamza Ghazouani on 19/05/2016.
// Copyright © 2016 Hamza Ghazouani. All rights reserved.
//
import UIKit
#IBDesignable
class LayoutConstraint: NSLayoutConstraint {
#IBInspectable
var 📱3¨5_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 480 {
constant = 📱3¨5_insh
}
}
}
#IBInspectable
var 📱4¨0_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 568 {
constant = 📱4¨0_insh
}
}
}
#IBInspectable
var 📱4¨7_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 667 {
constant = 📱4¨7_insh
}
}
}
#IBInspectable
var 📱5¨5_insh: CGFloat = 0 {
didSet {
if UIScreen.main.bounds.maxY == 736 {
constant = 📱5¨5_insh
}
}
}
}
Don't forgot to inherit your class constraint from ConstraintLayout
I will add the objective-c version soon

The basic tool in Auto Layout to manage UI objects' position is the Constraints. A constraint describes a geometric relationship between two views. For example, you might have a constraint that says:
“The right edge of progress bar is connected to the left edge of a lable 40 points of empty space between them.”
This means using AutoLayout you can't do conditional position setting based on UIDevice's mode, rather you can create a view layout which modifies itself if eg. the app runs on 3.5' full screen (IPhone4) or 4' full screen (IPhone5) based on the constraints.
So options for your problem using Constraints:
1) find a view on your layout which can be used to create a constraint to position the progressbar relatively. (select the view and the progressbar using CMD button, then use Editor/Pin/Vertical Spacing menu item to create a vertical constraint between the 2 objects)
2) create an absolute constraint to stick the progressbar's position to screen edge (keeping space) or centrally
I found helpful this tutorial about AutoLayout which might be beneficial for you also:
http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2
Pls note: autolayout only works from IOS 6.

The new way, Without writing a single line!
No need to write device based conditions like these :-
if device == iPhoneSE {
constant = 44
} else if device == iPhone6 {
constant = 52
}
I created a library Layout Helper so now you can update constraint for each device without writing a single line of code.
Step 1
Assign the NSLayoutHelper to your constraint
Step 2
Update the constraint for the device you want
Step 3
Run the app and see the MAGIC

I generally always try to stay in Interface Builder for setting up constraints. Diving in code to have more control is usually useful if you have completely different layouts on iPhone 4 and 6 for example.
As mentioned before, you can't have conditionals in Interface Builder, that's when linking a constraint to your view controller really comes handy.
Here's a short explanation on 3 approaches to solve Auto Layout issues for different screen sizes: http://candycode.io/how-to-set-up-different-auto-layout-constraints-for-different-screen-sizes/

Related

Using Swift, how do I animate the .setPosition() method of an NSSplitView without visually stretching its contents?

I would like to animate the appearance of a NSSplitViewItem using .setPosition() using Swift, Cocoa and storyboards. My app allows a student to enter a natural deduction proof. When it is not correct, an 'advice view' appears on the right. When it is correct, this advice view will disappear.
The code I'm using is the below, where the first function makes the 'advice' appear, and the second makes it disappear:
func showAdviceView() {
// Our window
let windowSize = view.window?.frame.size.width
// A CGFloat proportion currently held as a constant
let adviceViewProportion = BKPrefConstants.adviceWindowSize
// Position is window size minus the proportion, since
// origin is top left
let newPosition = windowSize! - (windowSize! * adviceViewProportion)
NSAnimationContext.runAnimationGroup { context in
context.allowsImplicitAnimation = true
context.duration = 0.75
splitView.animator().setPosition(newPosition, ofDividerAt: 1)
}
}
func hideAdviceView() {
let windowSize = view.window?.frame.size.width
let newPosition = windowSize!
NSAnimationContext.runAnimationGroup{ context in
context.allowsImplicitAnimation = true
context.duration = 0.75
splitView.animator().setPosition(newPosition, ofDividerAt: 1)
}
}
My problem is that the animation action itself is causing the text in the views to stretch, as you can see in this example: Current behaviour
What I really want is the text itself to maintain all proportions and slide gracefully in the same manner that we see when the user themselves moves the separator: Ideal behaviour (but to be achieved programmatically, not manually)
Thus far in my troubleshooting process, I've tried to animate this outside of NSAnimationContext; played with concurrent drawing and autoresizing of subviews in XCode; and looked generally into Cocoa's animation system (though much of what I've read doesn't seem to have direct application here, but I might well be misunderstanding it). I suspect what's going on is that the .animator() proxy object allows only alpha changes and stretches---redrawing so that text alignment is honoured during the animation might be too non-standard. My feeling is that I need to 'trick' the app into treating the animation as though it's being performed by the user, but I'm not sure how to go about that.
Any tips greatly appreciated...
Cheers

Added subview is positioned slightly off - how can I get it back into place?

UPDATE: Solved! While the contentMode for pianoNoteDisplayed and piano_background were indeed the same, apparently this wasn't true for the added subviews. I simply added the line subview.contentMode = superview.contentMode to the function vdmzz suggested, and now everything looks right on all 4 screen sizes.
There are two image views: one called "piano_background" holds a background image (a piano keyboard) and the other will be used to display highlighted notes. The second is constrained to the first:
(the width constraint is probably unnecessary, because the leading and trailing constraints are already set, right?)
To display multiple highlighted keys, I am programmatically adding subviews to the piano_note view and activating the NSLayoutConstraints to get it into place (otherwise it shows up way out of position) like so:
pianoNoteDisplayed.image = nil
if !notesAlreadyAttempted.contains(currentUserAnswer) {
let wrongNoteImageName = "large_\(currentUserAnswer)_wrong"
let wrongNoteImage = UIImage(named: wrongNoteImageName)
let wrongNoteImageView = UIImageView(image: wrongNoteImage!)
wrongNoteImageView.translatesAutoresizingMaskIntoConstraints = false
pianoNoteDisplayed.addSubview(wrongNoteImageView)
NSLayoutConstraint.activate([
wrongNoteImageView.widthAnchor.constraint(equalToConstant: pianoNoteDisplayed!.frame.width),
wrongNoteImageView.heightAnchor.constraint(equalToConstant: pianoNoteDisplayed!.frame.height)
])
}
notesAlreadyAttempted.append(currentUserAnswer)
}
The issue is that the subview is displayed slightly off, and I can't seem to figure out why:
(as you can see, the highlight looks slightly compressed vertically.. the top lands correctly, but the bottom doesn't reach far enough by about 5px)
I have tried centering and constraining the subview in multiple ways, using suggestions from about 5 different answers on stack, and a few other articles I found. The images I am using (the piano background and the overlaying note highlight subview) are identical sizes. I have tried adding more or fewer constraints in the interface builder, and I have tried adding subviews to the original piano_background view instead of the second pianoNoteDisplayed view - same result. Using the pianoNoteDisplayed view itself to display the highlighted note works fine by the way:
And these are displayed using the usual .image method:
pianoNoteDisplayed.image = UIImage(named: "large_\(currentCorrectAnswer)_right")
Any suggestions for how to troubleshoot the issue further?
First of all, as far as I understood pianoNoteDisplayed doesn't need to be an UIImageView.
Secondly, if you align piano_background and pianoNoteDisplayed by top, leading, trailing and bottom edges, one will be exactly on top of other. Or you could set them equal height, width and center positions.
The problem with your current set of constraints is that piano_background's Y position is determined by Safe Area and therefore might defer from pianoNoteDisplayed's Y position.
Try using this function:
func addSameSize(subview: UIView, onTopOf superview: UIView) {
superview.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
subview.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
subview.widthAnchor.constraint(equalTo: superview.widthAnchor).isActive = true
subview.heightAnchor.constraint(equalTo: superview.heightAnchor).isActive = true
subview.contentMode = superview.contentMode
}
E.g.
addSameSize(subview: wrongNoteImageView, onTopOf: pianoNoteDisplayed)
It will add your image views exactly aligned on top of pianoNoteDisplayed view

How to programmatically change constraint constants?

I read related questions(with nearly same titles), but it's not my case. I have a MKMapView and in the bottom of the screen i have ScrollView and ImageView. They are hidden, but when i show them i want to change bottom constraint of my MapView. The problem is, when i update bottom constraint, my MapView ignores it - i made ScrollView and ImageView transparent to check it - and even scrolls up, i don't understand why. My code for updating constant is this:
bt.flyImg.isHidden = true
bt.mapBottom.constant -= bt.flyImg.height
bt.view.layoutIfNeeded()
bt.flyImg.isHidden = false
bt.mapBottom.constant += bt.flyImg.height
bt.view.layoutIfNeeded()
I checked the constraint, it's the constraint i need. I tried to write something like
func layout()
{
self.view.layoutIfNeeded()
}
because i thought it might happen because i tried to update constant from other class, but it didn't help. What am i doing wrong?
The first thing you should do is to check if the constraint is still connected to mapBottom from the Connections Inspector (if you are using Storyboard). If it is and it is still not working, then you can try the alternative approach where you update the MapView's bottom constraint from the constarint's superview.
For this to work you must be able to identify the MapView's bottom constraint by giving it an identifier. To do that, look through the MapView's constraints in the Storyboard's Document Outline, find the bottom constraint, go over to the Size Inspector and give the constraint an identifier, let's say "MapViewBottom".
Now you must look through the MapView's superview constraints, identify the correct one and change the constant.
for constraint in yourMapView.superview!.constraints {
if constraint.identifier == "MapViewBottom" {
constraint.constant = flyImg.isHidden ? -flyImg.height : flyImg.height
}
}
You can then call the view to recalculate constraints if needed
view.layoutIfNeeded()
I think you might have initially decrease the constant of mapBottom to the height of flyImg. Instead of bt.mapBottom.constant -= bt.flyImg.height, change it to its default constant value. If it is pinned to sides of screen than make it
bt.flyImg.isHidden = true
bt.mapBottom.constant = 0 //if default value is 0. Just check it on storyboard.
bt.view.layoutIfNeeded()
bt.flyImg.isHidden = false
bt.mapBottom.constant += bt.flyImg.height
bt.view.layoutIfNeeded()
If it is still not working, Please insert detail source code so that we could figure out what's the matter.

Navigation based on screen orientation (landscape or portrait) in Flash CS6

I'm creating an app that will have a different menu if the phone is held landscape, or portrait.
I figure I have to tell flash to move to a new frame when the phone moves from landscape to portrait or vice versa, but I'm not sure the exact code to after creating the orientation event listener.
There are two ways. Listen for a StageOrientationEvent or listen for Event.RESIZE. I personally prefer to use RESIZE as it is called slightly more often and keeps your interface in sync more.
var landscapeNav:Sprite; // this would be your landscape nav. Obviously does not have to be a Sprite
var portraitNav:Sprite; // same as landscapeNav, but this represents your portrait nav
stage.addEventListener( Event.RESIZE, this.stageResizeHandler );
function stageResizeHandler( e:Event ):void {
if ( stage ) { //just to make sure the stage is loaded in this class so we avoid null refs
if ( stage.stageWidth >= stage.stageHeight ) {
landscapeNav.visible = true;
portraitNav.visible = false;
}
else {
landscapeNav.visible = false;
portraitNav.visible = true;
}
}
}
This could definitely be cleaned up (landscapeNav.visible = stage.stageWidth > stage.stageHeight) but this should give you something to go on. If you want to do an animation as Atriace suggested, you would do a TweenLite/Max call within the conditional in the function instead of setting visible to true/false (after the animation is done, though, you should set visible to false just for the same of optimzation)
You don't need to create a new frame. In fact, it may be more visually appealing to watch the old menu slide off, and the new one to animate in (like with TweenLite).
The documentation on orientation change can be found # Adobe's ActionScript APIs specific to mobile AIR applications: "Screen Orientation", and the API.

iOS UIScrollView Lazy Loading

i was just wondering if someone could explain this code for me so i can actually learn from it. I am trying to make my app have a scroller that scrolls left to right with loads of pictures (from internet) but the thing is, it must have lazy loading. so i did some tutorials and figured out how to do it but i truly don't understand it. So i was hoping some kind soul would explain how to lazy load step by step
This is the code i had learned from the tutorials:
-(void)scrollViewDidScroll:(UIScrollView *)myScrollView {
/**
* calculate the current page that is shown
* you can also use myScrollview.frame.size.height if your image is the exact size of your scrollview
*/
int currentPage = (myScrollView.contentOffset.y / currentImageSize.height);
// display the image and maybe +/-1 for a smoother scrolling
// but be sure to check if the image already exists, you can do this very easily using tags
if ( [myScrollView viewWithTag:(currentPage +1)] ) {
return;
}
else {
// view is missing, create it and set its tag to currentPage+1
}
/**
* using your paging numbers as tag, you can also clean the UIScrollView
* from no longer needed views to get your memory back
* remove all image views except -1 and +1 of the currently drawn page
*/
for ( int i = 0; i < currentPages; i++ ) {
if ( (i < (currentPage-1) || i > (currentPage+1)) && [myScrollView viewWithTag:(i+1)] ) {
[[myScrollView viewWithTag:(i+1)] removeFromSuperview];
}
}
}
About Lazy loading on scrollView, I would greatly advised to use UITableView instead. Apple did a great job with performance on this component.
You can have them horizontal (see this EasyTableView code, it works great) and stop the page mode if you want a continuous scroll (pagingEnabled = NO;) so you'll be able to get the behavior you are looking for.
Lazy loading is basically fetching large pieces of data (lets say images in this example) only when you need them. In your code, you have a delegate method that is called when you scroll a UIScrollView.
The -(void)scrollViewDidScroll:(UIScrollView *)myScrollView function decides when to actually get data. So as your scrolling, you find out where you are in the scroll view (say you have 10 images you want to load-- you want to know if the screen is currently showing image number 1, 2, 3, etc.). This is what the currentPage integer holds.
Now that you know which page you're looking at, we want to actually fetch the image.
if ( [myScrollView viewWithTag:(currentPage +1)] ) {
return;
}
The code above checks if the image AFTER the image the person is currently looking at exists (hence the currentPage + 1). If it does, we've already fetched it and we quit the function. Otherwise:
else {
// view is missing, create it and set its tag to currentPage+1
}
Here, we lazy load the image. This is done, for example, by creating a new thread and downloading the image from a server. We do this while the view is not the currentPage because we don't want the image to "pop in" while the user is scrolling. The view to which we add the image gets a tag (UIView has a "tag" property); we set the tag to currentPage+1, which later allows us to index the view in case we need it.
Finally, we have:
/**
* using your paging numbers as tag, you can also clean the UIScrollView
* from no longer needed views to get your memory back
* remove all image views except -1 and +1 of the currently drawn page
*/
for ( int i = 0; i < currentPages; i++ ) {
if ( (i < (currentPage-1) || i > (currentPage+1)) && [myScrollView viewWithTag:(i+1)] ) {
[[myScrollView viewWithTag:(i+1)] removeFromSuperview];
}
}
Here, we use our currentPage variable and iterate through all our views by indexing them by the tag we set. If the tag is not one off from the currentPage (remember, we don't want any pop in!) we remove it from the scrollview and free some memory up.
Hope that helped.
Perhaps this will help you.
Downloads the Asynchronous ImageView files from here https://github.com/nicklockwood/AsyncImageView/ and include them into your project.
Drag the ImageView on xib file and change it's class to AsynchronousImageView rather than UIImageView
Write this in you .h file
IBOutlet AsynchronousImageView *_artworkImg;
Write this in your .m file
[_artworkImg loadImageFromURLString:#"Your Image Url"];