Code Monkey home page Code Monkey logo

purelayout's Introduction

PureLayout

Build Status Version Platform License

The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. PureLayout extends UIView/NSView, NSArray, and NSLayoutConstraint with a comprehensive Auto Layout API that is modeled after Apple's own frameworks. PureLayout is a cross-platform Objective-C library that works (and looks!) great in Swift. It is fully backwards-compatible with all versions of iOS and OS X that support Auto Layout.

Writing Auto Layout code from scratch isn't easy. PureLayout provides a fully capable and developer-friendly interface for Auto Layout. It is designed for clarity and simplicity, and takes inspiration from the AutoLayout UI options available in Interface Builder while delivering far more flexibility. The API is also highly efficient, as it adds only a thin layer of third party code and is engineered for maximum performance.

Table of Contents

  1. Setup
  2. API Cheat Sheet
  3. Usage
  1. PureLayout vs. the rest
  2. Problems, Suggestions, Pull Requests?

Setup

Compatibility

The current release of PureLayout supports all versions of iOS and OS X since the introduction of Auto Layout on each platform, in both Swift and Objective-C, with a single codebase!

  • Xcode
    • Language Support: Swift (any version), Objective-C
    • Fully Compatible With: Xcode 7.0
    • Minimum Supported Version: Xcode 5.0
  • iOS
    • Fully Compatible With: iOS 9.0
    • Minimum Deployment Target: iOS 6.0
  • OS X
    • Fully Compatible With: OS X 10.11
    • Minimum Deployment Target: OS X 10.7

Using CocoaPods

  1. Add the pod PureLayout to your Podfile.
pod 'PureLayout'
  1. Run pod install from Terminal, then open your app's .xcworkspace file to launch Xcode.
  2. Import the PureLayout.h umbrella header.
  • With use_frameworks! in your Podfile
    • Swift: import PureLayout
    • Objective-C: #import <PureLayout/PureLayout.h> (or with Modules enabled: @import PureLayout;)
  • Without use_frameworks! in your Podfile
    • Swift: Add #import "PureLayout.h" to your bridging header.
    • Objective-C: #import "PureLayout.h"

That's it - now go write some beautiful Auto Layout code!

Using Carthage

  1. Add the PureLayout/PureLayout project to your Cartfile.
github "PureLayout/PureLayout"
  1. Run carthage update, then follow the additional steps required to add the framework into your project.
  2. Import the PureLayout framework/module.
  • Swift: import PureLayout
  • Objective-C: #import <PureLayout/PureLayout.h> (or with Modules enabled: @import PureLayout;)

That's it - now go write some beautiful Auto Layout code!

Manually from GitHub

  1. Download the source files in the PureLayout subdirectory.
  2. Add the source files to your Xcode project.
  3. Import the PureLayout.h header.
  • Swift: Add #import "PureLayout.h" to your bridging header.
  • Objective-C: #import "PureLayout.h"

That's it - now go write some beautiful Auto Layout code!

App Extensions

To use PureLayout in an App Extension, you need to do a bit of extra configuration to prevent usage of unavailable APIs. Click here for more info.

Releases

Releases are tagged in the git commit history using semantic versioning. Check out the releases and release notes for each version.

API Cheat Sheet

This is just a handy overview of the core API methods. Explore the header files for the full API, and find the complete documentation above the implementation of each method in the corresponding .m file. A couple of notes:

  • All of the public API methods are namespaced with the prefix auto..., which also makes it easy for Xcode to autocomplete as you type.
  • Methods that create constraints also automatically install (activate) the constraint(s), then return the new constraint(s) for you to optionally store for later adjustment or removal.
  • Many methods below also have a variant which includes a relation: parameter to make the constraint an inequality.

Attributes

PureLayout defines view attributes that are used to create auto layout constraints. Here is an illustration of the most common attributes.

There are 5 specific attribute types, which are used throughout most of the API:

  • ALEdge
  • ALDimension
  • ALAxis
  • ALMargin available in iOS 8.0 and higher only
  • ALMarginAxis available in iOS 8.0 and higher only

Additionally, there is one generic attribute type, ALAttribute, which is effectively a union of all the specific types. You can think of this as the "supertype" of all of the specific attribute types, which means that it is always safe to cast a specific type to the generic ALAttribute type. (Note that the reverse is not true -- casting a generic ALAttribute to a specific attribute type is unsafe!)

- autoSetContent(CompressionResistance|Hugging)PriorityForAxis:
- autoCenterInSuperview(Margins) // Margins variant iOS 8.0+ only
- autoAlignAxisToSuperview(Margin)Axis: // Margin variant iOS 8.0+ only
- autoPinEdgeToSuperview(Edge:|Margin:)(withInset:) // Margin variant iOS 8.0+ only
- autoPinEdgesToSuperview(Edges|Margins)(WithInsets:)(excludingEdge:) // Margins variant iOS 8.0+ only
- autoPinEdge:toEdge:ofView:(withOffset:)
- autoAlignAxis:toSameAxisOfView:(withOffset:|withMultiplier:)
- autoMatchDimension:toDimension:ofView:(withOffset:|withMultiplier:)
- autoSetDimension(s)ToSize:
- autoConstrainAttribute:toAttribute:ofView:(withOffset:|withMultiplier:)
- autoPinTo(Top|Bottom)LayoutGuideOfViewController:withInset: // iOS only
- autoPinEdgeToSuperviewSafeArea: // iOS 11.0+ only
- autoPinEdgeToSuperviewSafeArea:withInset: // iOS 11.0+ only
// Arrays of Constraints
- autoInstallConstraints
- autoRemoveConstraints
- autoIdentifyConstraints: // iOS 7.0+, OS X 10.9+ only

// Arrays of Views
- autoAlignViewsToEdge:
- autoAlignViewsToAxis:
- autoMatchViewsDimension:
- autoSetViewsDimension:toSize:
- autoSetViewsDimensionsToSize:
- autoDistributeViewsAlongAxis:alignedTo:withFixedSpacing:(insetSpacing:)(matchedSizes:)
- autoDistributeViewsAlongAxis:alignedTo:withFixedSize:(insetSpacing:)
+ autoCreateAndInstallConstraints:
+ autoCreateConstraintsWithoutInstalling:
+ autoSetPriority:forConstraints:
+ autoSetIdentifier:forConstraints: // iOS 7.0+, OS X 10.9+ only
- autoIdentify: // iOS 7.0+, OS X 10.9+ only
- autoInstall
- autoRemove

Usage

Sample Code (Swift)

PureLayout dramatically simplifies writing Auto Layout code. Let's take a quick look at some examples, using PureLayout from Swift.

Initialize the view using PureLayout initializer:

let view1 = UIView(forAutoLayout: ())

If you need to use a different initializer (e.g. in UIView subclass), you can also use configureForAutoLayout:

view1.configureForAutoLayout() // alternative to UIView.init(forAutoLayout: ())

Here's a constraint between two views created (and automatically activated) using PureLayout:

view1.autoPinEdge(.top, toEdge: .bottom, ofView: view2)

Without PureLayout, here's the equivalent code you'd have to write using Apple's Foundation API directly:

NSLayoutConstraint(item: view1, attribute: .top, relatedBy: .equal, toItem: view2, attribute: .bottom, multiplier: 1.0, constant: 0.0).active = true

Many APIs of PureLayout create multiple constraints for you under the hood, letting you write highly readable layout code:

// 2 constraints created & activated in one line!
logoImageView.autoCenterInSuperview()

// 4 constraints created & activated in one line!
textContentView.autoPinEdgesToSuperviewEdges(with insets: UIEdgeInsets(top: 20.0, left: 5.0, bottom: 10.0, right: 5.0))

PureLayout always returns the constraints it creates so you have full control:

let constraint = skinnyView.autoMatchDimension(.height, toDimension: .width, ofView: tallView)

PureLayout supports safearea with iOS 11.0+:

view2.autoPinEdge(toSuperviewSafeArea: .top)

PureLayout supports all Auto Layout features including inequalities, priorities, layout margins, identifiers, and much more. It's a comprehensive, developer-friendly way to use Auto Layout.

Check out the example apps below for many more demos of PureLayout in use.

Example Apps

Open the project included in the repository (requires Xcode 6 or higher). It contains iOS (Example-iOS scheme) and OS X (Example-Mac scheme) demos of the library being used in various scenarios. The demos in the iOS example app make a great introductory tutorial to PureLayout -- run each demo, review the code used to implement it, then practice by making some changes of your own to the demo code.

Each demo in the iOS example app has a Swift and Objective-C version. To compile & run the Swift demos, you must use Xcode 7.0 or higher (Swift 2.0) and choose the Example-iOS-Xcode7 scheme. When you run the example app, you can easily switch between using the Swift and Objective-C versions of the demos. To see the constraints in action while running the iOS demos, try using different device simulators, rotating the device to different orientations, as well as toggling the taller in-call status bar in the iOS Simulator.

On OS X, while running the app, press any key to cycle through the demos. You can resize the window to see the constraints in action.

Tips and Tricks

Check out some Tips and Tricks to keep in mind when using the API.

PureLayout vs. the rest

There are quite a few different ways to implement Auto Layout. Here is a quick overview of the available options:

  • Apple NSLayoutConstraint SDK API
    • Pros: Raw power
    • Cons: Extremely verbose; tedious to write; difficult to read
  • Apple Visual Format Language
    • Pros: Concise; convenient
    • Cons: Doesn't support some use cases; lacks compile-time checking and safety; must learn syntax; hard to debug
  • Apple Interface Builder
    • Pros: Visual; interactive; provides compile-time layout checking
    • Cons: Difficult for complex layouts; cannot dynamically set constraints at runtime; encourages hardcoded magic numbers; not always WYSIWYG
  • Apple NSLayoutAnchor SDK API
    • Pros: Clean, readable, and type-safe API for creating individual constraints
    • Cons: Only available in iOS 9.0 and OS X 10.11 and higher; requires manually activating each constraint; no API for creating multiple constraints at once
  • PureLayout
    • Pros: Compatible with Objective-C and Swift codebases; consistent with Cocoa API style; cross-platform API and implementation shared across iOS and OS X; fully backwards-compatible to iOS 6 & OS X 10.7; easy to use; type-safe; efficient
    • Cons: Not the most concise expression of layout code
  • High-level Auto Layout Libraries/DSLs (Cartography, SnapKit, KeepLayout)
    • Pros: Very clean, concise, and convenient
    • Cons: Unique API style is foreign to Apple's APIs; mixed compatibility with Objective-C & Swift; greater dependency on third party code

PureLayout takes a balanced approach to Auto Layout that makes it well suited for any project.

Problems, Suggestions, Pull Requests?

Please open a new Issue here if you run into a problem specific to PureLayout, have a feature request, or want to share a comment. Note that general Auto Layout questions should be asked on Stack Overflow.

Pull requests are encouraged and greatly appreciated! Please try to maintain consistency with the existing code style. If you're considering taking on significant changes or additions to the project, please communicate in advance by opening a new Issue. This allows everyone to get onboard with upcoming changes, ensures that changes align with the project's design philosophy, and avoids duplicated work.

Meta

Originally designed & built by Tyler Fox (@smileyborg). Currently maintained by Mickey Reiss (@mickeyreiss). Distributed with the MIT license.

purelayout's People

Contributors

adrum avatar alyakan avatar antondomashnev avatar arsonik avatar himaratsu avatar iby avatar javitrujillo avatar jjksam avatar joshintu avatar jp26jp avatar karlpuusepp avatar lkraider avatar lutzifer avatar lwdupont avatar masatomizuta avatar mickeyreiss avatar mortonfox avatar pallzoltan avatar pnc avatar revolter avatar seth-admittedly avatar sger avatar smileyborg avatar steffendsommer avatar therzok avatar tmrayle avatar tomhamming avatar toohotz avatar vivianforzj avatar vladislav-eero avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

purelayout's Issues

Add parameter to add priority onto constraint

In iOS 7, it was possible to create an NSLayoutConstraint and then modify it's priority property after it was added to a view.

For example you could do:

NSLayoutconstraint *labelConstraint = [myView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
labelConstraint.priority = UILayoutPriorityDefaultLow;

In iOS 8, this will throw an NSInternalInconsistencyException, saying Mutating a priority from required to not on an installed constraint (or vice-versa) is not supported

The solution is to add the priority before calling autoInstall. To do this, I would recommend adding priority as a parameter that you can pass in when auto creating a constraint.

I've had to switch back to doing manual constraints for now, but if I am correct, that would fix the crashes. Let me know if you need any more information, love the library.

Setting a view hidden doesn't remove constraints.

Hey, @smileyborg.

I've been struggling for some time on this and still didn't come up with a normal workaround.

Imagine you have a TableView with some custom cells. There are 3 labels in the cell.
The first one is pinned to the top.
The second one is in the middle.
The third one is pinned to the bottom.
You want the cell to have dynamic height depending on the content inside it.

Done. Everything works great with PureLayout.

Now you want to hide the middle label and set hidden = YES. The label gets hidden, but not from auto layout! so the height of the cell doesn't collapse it stays as if the label is still there.

If you've had an issue like this and know a workaround please tell me how you managed it. I'm a bit desperate at the moment:)

Proper way to centering views on superview.

        NSArray *buttons = @[button1, button2];
        [buttons autoSetViewsDimension:ALDimensionWidth toSize:ElementsWidth];
        [buttons autoSetViewsDimension:ALDimensionHeight toSize:ElementsHeight];
        [button1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self withOffset:-ElementsHeight + ElementsSpacing/2];
        [button2 autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:button1 withOffset:ElementsSpacing];
        [button1 autoAlignAxisToSuperviewAxis:ALAxisVertical];
        [button2 autoAlignAxisToSuperviewAxis:ALAxisVertical];

Suggestions?

Using PureLayout with Size Classes?

Hello!

When using auto layout in Interface Builder, you can have some constraints only apply in certain orientations (and certain devices). For example, you can use this to have certain elements appear in Landscape mode and collapse in portrait mode. Is there a good way to do this with PureLayout in code?

Thanks for any thoughts!

Inconsistent Constraints (with and without animations)

I believe that I have found a bug of sorts, but this could be due to some lack of understanding that I possess.. I've created an example project that displays the issue.

Here is the project: https://github.com/bhowell2/PureLayoutExample

Hierarchy:
MainControllerView (full screen)
-ChildControllerView (full screen) (just covers main view)
-SearchFieldView (top 6% (height) of screen and 100% width)
-SearchField (takes up 80% of width of superview and 100% height and is offset from the left by 20)
-ActivityIndicator
-TagScrollView (bottom 94% (height) of screen and 100% width) (scrollview)

You can see the issue when you click load view in the navigation bar. The first time, the view loads as expected. The second time you click load view, two things happen. The top view controller (that should take up 6% height and 100% width) shifts to the left (revealing the brown view beneath). I really have no idea why this is. NOT ONLY does this happen, but the view resizes itself to like 1/4th of the screen...

You will notice that this does not happen when using Apple's (verbose) layout constraints.. (though there is an issue where the brown view appears too quickly.. ignore that for now!)

You may test this by setting usePureLayout in MainViewController.

You can use the animation by setting useAnimations in MainViewController as well.

I first noticed the top view shifting to the left when implementing this without an animation. When i introduced the animation it got really crazy where the view appeared at about 1/4 screen size... (And i just noticed that now it's going to 1/4 screen size with or without the animation)

Any ideas what is going on here? Am I simply setting something wrong?

(I actually made this little project to try to reproduce the top view shifting to the left that i noticed in my own project, but could not get it to reproduce here.. it showed back up when i introduced the animations -and you can see it, by the brown view beneath showing, when it's at 1/4 size, now regardless of animations)

How to get superview's frame?

If I set subviews' constraints and pin to edges of superview, how and when can I get the superview's frame? Specifically in Table View Cell?

Thanks.

purelayout 2.0.x not support xcode 5.0.2

when i try to build my project using xcode 5.0.2 , sdk ios 7, yosemite, i got so many errors

/Users/user/xxx/Pods/PureLayout/Source/PureLayoutDefines.h:140:24: Use of undeclared identifier 'NSLayoutAttributeTrailingMargin'; did you mean 'NSLayoutAttributeTrailing'?

autoInstall constraint with lower priority crashes

I have face this issue when updating to the new version and start using this new method (thanks for your amazing library!). I have a constraint with priority 750 and when I send a message to autoInstall it crashes because it is trying to set the priority to 1000

I have tried to fix this issue with this:

+ (void)al_applyGlobalStateToConstraint:(NSLayoutConstraint *)constraint
{
    constraint.priority = _al_globalConstraintPriority <= constraint.priority ? _al_globalConstraintPriority : constraint.priority;
#if __PureLayout_MinBaseSDK_iOS8
    [constraint autoIdentify:_al_globalConstraintIdentifier];
#endif /* __PureLayout_MinBaseSDK_iOS8 */
}

Makes sense to pick up the proper priority, test passes but in my project the app keeps crashing. By removing constraint.priority = _al_globalConstraintPriority it works just fine (it will remain with the same priority that it should, but that way PureLayoutTests do not pass). Any help here?

Thanks!

Are there any gotchas when updating from UIView+Autolayout?

as far as I can see, the API is the same. It would be great if you could post a note to let us know whether this is a drop-in replacement, or whether we have to watch out for specific changes.

thanks for a great tool, I use it in all my apps now.

why the lable don't center in such constraints?

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.translatesAutoresizingMaskIntoConstraints=NO;
    UIScrollView* scrollview=[[UIScrollView alloc] init];
    self.sview=scrollview;
    scrollview.translatesAutoresizingMaskIntoConstraints=NO;
    [scrollview setPagingEnabled:YES];
    [scrollview setShowsVerticalScrollIndicator:NO];
    [scrollview setShowsHorizontalScrollIndicator:YES];
    [self.view addSubview:scrollview];

    UIView* conview=[[UIView alloc] init];
    self.cview=conview;
    conview.translatesAutoresizingMaskIntoConstraints=NO;
    [scrollview addSubview:conview];

    NSDictionary* views=@{@"conview":conview,@"scrollview":scrollview};
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollview]|" options:0 metrics:0 views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollview]|" options:0 metrics:0 views:views]];

    [scrollview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[conview]|" options:0 metrics:0 views:views]];
    [scrollview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[conview]|" options:0 metrics:0 views:views]];

    UILabel* label=[[UILabel alloc] init];
    label.translatesAutoresizingMaskIntoConstraints=NO;
    label.text=@"abcd";
    label.textAlignment=NSTextAlignmentCenter;
    [conview addSubview:label];

    [conview addConstraint:[ NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:conview attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
    NSDictionary* dic=@{@"label":label};
    [conview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:dic]];
    [conview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|" options:0 metrics:nil views:dic]];

}

README updates

  • Add setup instructions for Swift (e.g. bridging header)
  • Add some sample code to README (Swift & Objective-C) so casual readers get a feel for the syntax
  • Add links to Swift sample project
  • Put setup instructions at top above cheat sheet
  • Add a "table of contents" with links to sections of the README

Dynamic cell height in pure layout

bildschirmfoto 2014-11-06 um 19 23 12

I want the table cell to grow depending on the content. As you can see from this picture the first cell has a big gap. I pretty much used your https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8 project.

The only thing I changed was

titleLabel.numberOfLines = 1

to

titleLabel.numberOfLines = 0

because the title may have variable length. And I get the result like you see in the picture. Any ideas whats wrong? Maybe the constrains don't find my use case?

titleLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: kLabelVerticalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)

bodyLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: titleLabel, withOffset: 10.0, relation: .GreaterThanOrEqual)

bodyLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: kLabelVerticalInsets)

any ideas?

No reference to superview crashes the app in iOS 8

I wanted to change storyboard contraints in code (removed at runtime ticked)

to problem is that i am basing on super view and my subview has property superview set only after viewWill/Did appear - which causes the subview to jump after it appears on user.

When I do it earlier it crashes hard

Help ruling out some issues with NSInternalInconsistencyException

PureLayout works fine when laying out items in a UINavigationBar on iOS 8.x +, but when building back for iOS 7.1 I'm not allowed to do that apparently:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot modify constraints for UINavigationBar managed by a controller'

Can I just get confirmation that this is or is not a purelayout issue or an autolayout issue.

TableView Footer doesn't float.

i added a footer to my UITableView using -(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

and i also wrote this: - (BOOL)allowsFooterViewToFloat{ return YES; }

still the footer doesn't float. How do i fix this?

Can I access any View's constraint at run time and change it?

Hi there,
I am new to autoLayout, and I am considering rewriting my project using pureLayout or other open source code, so I have to do some researching first.

One important thing is could I access any constraint at run time?

e.g. if I created below constraint:

[self.blueView autoSetDimension:ALDimensionHeight toSize:kBlueViewInitialHeight];

Could I access this Height constraint at run time? what's the API? Note I don't want to do things like

self.blueViewHeightConstraint = [self.blueView autoSetDimension:ALDimensionHeight toSize:kBlueViewInitialHeight];

because I don't want to store many properties. I just want change the height constraint at a given time and animate it. Thank you.

align centerlines of two views

I know this has to be possible, and I must just be missing this in the api documentation, but nonetheless I cannot figure this out using purelayout. I want viewA to align it's centerline to viewB.

Add new iOS 8 features

iOS 8 SDK adds some new things:

  • New layout attributes, including first baseline, and layout margin variants
  • active property on NSLayoutConstraint (and activateConstraints:/deactivateConstraints: methods) remove the need to manually add constraints to the right view
  • Explore automatically setting the identifier string on NSLayoutConstraints created by the API

These new features will be added in a fully backwards-compatible fashion.

Note: PureLayout is fully compatible with iOS 8 already. These are just new extensions to be added.

Ability to specify priority in autoSetDimension:toSize:relation:

This is more just a question. Why does the -[UIView autoSetDimension:toSize:relation:] method not have a variant that allows us to specify the priority of the constraint?

Use case - I've just come across a scenario where I have a complex subview and I need to compress the height of that subview as much as possible. The only approach I've found that works is installing a low priority constraint that sets the subview's height to zero. Not sure if this is good practice, but I've tried several other approaches without success, e.g. content hugging priority.

It would be nice if I could achieve this using the PureLayout API - I ended up resorting to the native NSLayoutConstraint API to achieve my goal.

P.S. thanks for the awesome library, I use it constantly

Carthage install fails due to header naming

If you use the latest Carthage and try to import PureLayout into your app, Xcode will fail to build the module, because the Modules/module.modulemap file points to PureLayout_iOS.h as the framework header, but the framework header is actually PureLayout.h. Currently thinking of the cleanest way to fix this.

(enhancement) Additional Methods

I have written some additional methods for AutoLayout (which will also work with PureLayout) which I've found to be extremely useful. I would like to contribute them to the project, but I'm having trouble figuring out GIT. Can I send them to the project manager?

NSArray+PureLayout.m produces an error when added to app extension target

This block of code from NSArray+PureLayout.m

#if TARGET_OS_IPHONE
    BOOL isRightToLeftLayout = [[UIApplication sharedApplication] userInterfaceLayoutDirection] == UIUserInterfaceLayoutDirectionRightToLeft;
#else
    BOOL isRightToLeftLayout = [[NSApplication sharedApplication] userInterfaceLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft;
#endif /* TARGET_OS_IPHONE */
    BOOL shouldFlipOrder = isRightToLeftLayout && (axis != ALAxisVertical); // imitate the effect of leading/trailing when distributing horizontally

produces the following error when added to app extension target:

/Users/zhixuanlai/Developer/Github/Emotic/Emotic/Emotic/Source/NSArray+PureLayout.m:383:48: 'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.

PureLayout & UICollectionView

Hey,

Great library - I've been enjoying using it to date, and my UITableViewsCells are resizing dynamically very nicely with many custom views. However, I have one issue when using UICollectionView. The iOS framework requires the collection view layout to be specified at initialisation time - as so :

self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,320.0f,50.0f) collectionViewLayout:layout];

If i try to use newAutoLayoutView or initForAutoLayout, i get the error 'UICollectionView must be initialized with a non-nil layout parameter'. Even if i use setCollectionViewLayout directly afterwards, it's still not working.

So, if I have to supply a frame at initialisation, how can this fit with purelayout?

Thanks so much in advance,
R

not compiling on OS X 10.7

unfortunately the latest master is not building on OS X 10.7 due to unrecognized selectors and properties:

NSArray+PureLayout.m:58:13: No known class method for selector 'activateConstraints:' 
NSArray+PureLayout.m:78:9: No known class method for selector 'deactivateConstraints:'
NSLayoutConstraint+PureLayout.m:52:18: Property 'active' not found on object of type   'NSLayoutConstraint *'
NSLayoutConstraint+PureLayout.m:119:14: Property 'identifier' not found on object of type 'NSLayoutConstraint *'

Is there any chance to fix this?

Thanks!

UILabel set height based on content but with a max limit

Hi guys,
I'm using PureLayout to make my code-based autolayout costraints.First of all thank your for these APIs.
However I've a question about the right constraints I need to set in order to have a label with dynamic height and max bounds in vertical axis.
Consider a label inside a superview: this label has the same width of the superview and height based on it's content; however I would add a limit to the height (the bottom side of the superview). So If the content is too much to be rendered in the space will be clipped.
That's my code:

- (void)updateConstraints {
    if (!constraintsApplied) {
        constraintsApplied = YES;
        [lblPlotSummary autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self withOffset:10];
        [lblPlotSummary autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self];
        [lblPlotSummary autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self withOffset:-30];

        [CRDiscoverHotMovieCell autoSetPriority:UILayoutPriorityFittingSizeLevel
                                 forConstraints:^{
                                     [lblPlotSummary autoSetContentHuggingPriorityForAxis:ALAxisVertical];
                                 }];
    }
    [super updateConstraints];
}


- (void)layoutSubviews {
    [super layoutSubviews];
    lblPlotSummary.preferredMaxLayoutWidth = lblPlotSummary.frame.size.width;
    [super layoutSubviews];
}

Now it works fine and the height of the label is based on it's content. However I cannot set the max height to the bottom of the superview.
How can I handle this?
I've tried manually setting it using:

[lblPlotSummary autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self withOffset:-5];

However it simply set the size to the max size and no consider the content of the text.

This is an example without the last line (it consider the height of the content but not the limit of the superview)

Imgur

And this is the example with that line (it does not consider the content and set the height to the bounds of the superview).

Imgur

Any idea?

Adding priority to a constraint

  • Is there a way to add explicit priority to a particular constraint before installing it?
  • I tried using [UIView autoSetPriority:forConstraints:] before setting constraints with no success.
  • Using ios framework, I understand that it's possible to setup constraint and change its priority and then install it. Is there a way, in PureLayout, to create the constraint without installing it? Or can we remove the constraint temporarily to change it's priority?
  • In particular, I want to add two similar constraints that differ only in 'relation' value to a view. And I need to give the constraints different priority.

Constraints not autoinstalled

I have a relatively simple set of constraints I am trying to fulfill (trying to keep a table view pinned to the visible regions of the screen, however, when trying to install the constraints, it does not seem to be installing any. I am creating the table view in pure code. Any ideas as to what the issue is?

// in init 
self.tableView = [[UITableView alloc] initForAutoLayout];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];

- (void)updateViewConstraints {
    if (!self.didSetupConstraints) {
       [self.tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeTop];
       NSLayoutConstraint *topLayoutConstraint = [self.tableView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.navigationController.navigationBar withOffset:0.0];

        NSLog(@"%@ constraints after auto installation: %@", self.tableView, self.tableView.constraints);

        self.didSetupConstraints = YES;
    }

    [super updateViewConstraints];
}

Output:

<UITableView: 0x157862400; frame = (0 0; 0 0); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x174252ab0>; layer = <CALayer: 0x174233180>; contentOffset: {0, 0}; contentSize: {0, 100}> constraints on setup: (
)

Continued unit test development

PureLayout is the successor of UIView+AutoLayout which has been extensively and thoroughly tested and proven on iOS.

The biggest difference between iOS and OS X is the inverted Y axis between the two coordinate systems.

For anyone using this project on OS X, I would appreciate feedback from your additional usage/functional testing to validate that there aren't any issues around the flipped Y axis.

As the unit test suite continues to be built out, coverage will improve on that front as well. (If you are interested in contributing some unit tests, that would be greatly appreciated!)

PureLayout v2.0.0 pre-release testing

Today is a massive day for PureLayout: commit f644e37 has been pushed to master, which rolls up a ton of API enhancements and improvements! 🎉

Before officially releasing v2.0.0 of PureLayout, I'd appreciate any feedback on the changes, as well as any help you can provide taking the new code for a spin.

The unit test library still needs more work, so if you're interested in truly being a rockstar and contributing to some unit test development, drop a note here and I'll help you get started!

Expect the v2.0.0 release to become official (with a pod update) in the next week.

autoDistributeViewsAlongAxis not working on device

Hi, I'm using this code

[views autoMatchViewsDimension:ALDimensionHeight];
[views autoDistributeViewsAlongAxis:ALAxisHorizontal alignedTo:ALAttributeHorizontal withFixedSpacing:10.0f];

to align a dynamic number of buttons inside a UIView. It works with all the simulated devices but not on real devices (tested: iPhone4, iPhone4S).

Use PureLayout on UIScrollview

hello, I try to use PureLayout on UIScrollview 。code example
[self.scrollview autoSetDimensionsToSize:CGSizeMake(Screen_width, 30)];
[self.scrollview autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.titleView];
[self.scrollview autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.titleView withOffset:74];

for(int i=0;i<6;i++){
    UIButton *btn = [UIButton newAutoLayoutView];
    [btn setBackgroundColor:[self.titleColor objectAtIndex:i]];
    [btn setTitle:[self.titleText objectAtIndex:i] forState:UIControlStateNormal];
    [self.scrollview addSubview:btn];
    [btn autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.scrollview];
    [btn autoSetDimensionsToSize:CGSizeMake(58, 20)];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [btn autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.scrollview withOffset:i*63];
    [btn autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.scrollview withOffset:0];
}
[self.scrollview setContentSize:CGSizeMake(65*6, 0)];

on ios8,scrollview can sliding,but on ios7 Can't sliding
please help! thank you!!!

Auto align axis horizontal vs vertical

This is surely the wrong way round?

case ALAxisVertical:
   layoutAttribute = NSLayoutAttributeCenterX;
   break;
case ALAxisHorizontal:
   layoutAttribute = NSLayoutAttributeCenterY;
   break;

Or perhaps I'm misunderstanding here? I would expect a horizontal axis alignment to centre along the X axis and a vertical axis alignment to centre along the Y axis.

autoDistributeViewsAlongAxis UITextFields

Hi!
I'm using PureLayout (1.1.0) and have noticed some unexpected behaviour with autoDistributeViewsAlongAxis.

I'm creating UITextFields

- (void)createPinTextView
{
  self.pinTextView = [[UIView alloc] init];

  for (int i = 0; i <= 4; i++) {
    UITextField *textField = [self createPinTextField];
    [self.pinTextFields addObject:textField];
    [self.pinTextView addSubview:textField];
  }

  [self.view addSubview:self.pinTextView];
}

And setting up constraints

- (void)updateViewConstraints
{
  [super updateViewConstraints];

  if (!self.didSetupContraints) {
    NSArray *pinViews = [self.pinTextFields subarrayWithRange:NSMakeRange(0, 5)];
    [pinViews.firstObject autoSetDimension:ALDimensionHeight toSize:40.0f];
    [pinViews autoMatchViewsDimension:ALDimensionHeight];

    [pinViews.lastObject autoAlignAxisToSuperviewAxis:ALAxisHorizontal];

    [pinViews autoDistributeViewsAlongAxis:ALAxisHorizontal
                          withFixedSpacing:18.0f
                              insetSpacing:YES
                                 alignment:NSLayoutFormatAlignAllCenterY];

    self.didSetupContraints = YES;
  }

Last UITextField font size don't match others.

Image of UITextField

UITextView in rowcell, automatic dimension

Hi,
i've used your example where show the usage of UITableViewAutomaticDimension and all works fine.

I've simply changed the UILabel(body) with an UITextView but the text in the UITextView not appear.

The title is set correctly, but the body is not show.

I've to setup something elese to use PureLayout with UITextView?

Thanks

how to vetical align center in viewcontroller?

Now I can use autoAlignAxisToSuperviewAxis:ALAxisHorizontal to vertical align center in superview. But how to vertical align center in viewcontroller? That is, vertical align center in remaining area besides navigation bar.
Thanks!

ALAxisVertical refers to horizontal centerX

centerX is really a horizontal axis isn't it? It's confusing.

[self.view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view2];

This in fact produces:

view1.centerX == view2.centerX

When I use lldb I query for horizontal axis to see that constraint:

po [self.view1 constraintsAffectingLayoutForAxis:UILayoutConstraintAxisHorizontal]

Example of working Swift code?

I read in the docs about a bridging header, but I don't see one in the files, and I am having a hard time incorporating PureLayout into my Swift project. What am I missing? A very small working proof-of-concept project would be welcome.
This looks like a great package; I'm eager to use it.
Thanks!

pin to edge of multiple views

Pinning to one view is easy:

[view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:last withOffset:offset]

but how do I give distance the union of two views (basically picking the lower one)?

Will PureLayout support arm64?

you know, after next Feb, apple will reject any app that doesn't support arm64. That means all third-party frameworks in my project need support arm64. PureLayout is a good framework, so will it support arm64 proccessor?

How to use pureLayout api add the topLayoutGuide constraints?

Hi:
How to use pureLayout api add the topLayoutGuide constraints?like this
[NSLayoutConstraint constraintWithItem:self.button
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.topLayoutGuide
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];

Right to left handling in autoDistribute... methods when distributing horizontally

I have noticed different behavior regarding right to left languages:

  • autoDistributeViewsAlongAxis:alignedTo:withFixedSpacing:insetSpacing:matchedSizes: uses trailing and leading edges when distributing horizontally. With RTL the last view in the array appears first.
  • autoDistributeViewsAlongAxis:alignedTo:withFixedSize:insetSpacing: iterates array backwards to maintain the order and result is independent of writing direction.

I think it would make sense to behave consistently in both methods or (imho a better way) have a flag controlling whether it flips the views or lets autolayout take care of it.

Would be happy to make a PR, but wanted to discuss before since it would introduce breaking and/or API changes.

Podfile issues

This doesn't appear to be your fault, but it is causing problems for me that would be hard to resolve.

I'm trying to lock into a version, 1.1.0, so my pod won't be updated, since I'm not ready to take the time and make a lot of code changes right now. The tag is v1.1.0, which is making the pod install process throw an error.

Other semantically versioned pods use a format of 1.1.0, which works fine. Before it wasn't necessary to worry about this because the changes weren't breaking changes, but with the 2.0 series they are.

Would it be possible to make a tag that is identical to v1.1.0, called 1.1.0, for the sake of making it work with pod install?

Thanks!

testPriorityForDistributingMultipleViews fails on Mac target

It seems that Travis is silent, but when building on my own machine (10.10.1 and Xcode 6.1) I get this exception in PureLayoutTests.m:259:

Test Case '-[PureLayoutPriorityTests testPriorityForDistributingMultipleViews]' started.
/Users/mnx/play/PureLayout/Example/PureLayoutTests/PureLayoutPriorityTests.m:259: error: -[PureLayoutPriorityTests testPriorityForDistributingMultipleViews] : failed: caught "NSInvalidArgumentException", "*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: A multiplier of 0 or a nil second item together with a location for the first attribute creates an illegal constraint of a location equal to a constant. Location attributes must be specified in pairs"
(
    0   CoreFoundation                      0x00007fff926f164c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff85bb66de objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff926f14fd +[NSException raise:format:] + 205
    3   Foundation                          0x00007fff92d50d76 VerifyConstraintArguments + 200
    4   Foundation                          0x00007fff92b1a7b2 +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:] + 399
    5   Example-Mac                         0x000000010000b654 -[NSArray(PureLayout) autoDistributeViewsAlongAxis:alignedTo:withFixedSize:insetSpacing:] + 1732
    6   PureLayoutTests-Mac                 0x00000001000b0c1e __67-[PureLayoutPriorityTests testPriorityForDistributingMultipleViews]_block_invoke205 + 110
    7   PureLayoutTests-Mac                 0x00000001000acd6e __66-[PureLayoutPriorityTests assertConstraints:areAddedWithPriority:]_block_invoke + 46
    8   Example-Mac                         0x0000000100005551 +[NSView(PureLayout) autoSetPriority:forConstraints:] + 417
    9   PureLayoutTests-Mac                 0x00000001000abe2d -[PureLayoutPriorityTests assertConstraints:areAddedWithPriority:] + 365
    10  PureLayoutTests-Mac                 0x00000001000ab9c1 -[PureLayoutPriorityTests assertConstraintsAreAddedWithDefaultPriorities:] + 449
    11  PureLayoutTests-Mac                 0x00000001000b0848 -[PureLayoutPriorityTests testPriorityForDistributingMultipleViews] + 360
    12  CoreFoundation                      0x00007fff925ca33c __invoking___ + 140
    13  CoreFoundation                      0x00007fff925ca192 -[NSInvocation invoke] + 290
    14  XCTest                              0x0000000100407919 -[XCTestCase invokeTest] + 253
    <...>
)

Everything works as expected on iOS target.

I can take a look at a possible solution, but I wonder why Travis doesn't see this issue?

Subclassed UIView not visible, however content is visible

I subclassed UIView: http://pastebin.com/MVk1XmPS and when I add it to another view of a UIViewController:

self.myView = MyView.newAutoLayoutView()
self.myView.backgroundColor = UIColor.redColor()
self.view.addSubview(self.myView)

the red background is missing. It seems that myView has no width and height. However the content is visible:

foto 07 11 14 23 12 36

I have to hard code the dimension:

self.myView.autoSetDimensionsToSize(CGSize(width: 100, height: 100))

but shouldn't it grow automatically by the size of the content?

Warnings in Example project when kLabelVerticalInsets >= 15.f

If I set kLabelVerticalInsets to anything more or equal than 15.f I get the following warnings in the console:

TableViewCellWithAutoLayout[19708:332390] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want...
(
"<NSLayoutConstraint:0x7fc42263c400 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fc422630e50(44)]>",
"<NSLayoutConstraint:0x7fc42263d4c0 V:|-(15)-[UILabel:0x7fc422631ed0'Marion'] (Names: '|':UITableViewCellContentView:0x7fc422630e50 )>",
"<NSLayoutConstraint:0x7fc42263d870 V:[UILabel:0x7fc422631ed0'Marion']-(>=15)-[UILabel:0x7fc4226324f0'Lorem ipsum dolor sit ame...']>",
"<NSLayoutConstraint:0x7fc42263c3b0 UILabel:0x7fc4226324f0'Lorem ipsum dolor sit ame...'.bottom == UITableViewCellContentView:0x7fc422630e50.bottom - 15>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7fc42263d870 V:[UILabel:0x7fc422631ed0'Marion']-(>=15)-[UILabel:0x7fc4226324f0'Lorem ipsum dolor sit ame...']>

Even though the message should be pretty clear I still don't understand what went wrong..
Thanks in advance.

No PureLayout Module

Hey @smileyborg

I've added the following to my bridging header
#import "PureLayout.h"

and am trying to do a import PureLayout into my Swift UIViewController, but get the following error on Xcode 6.0.2

'No such module PureLayout'

Is there a wrapper class, or similar that I need ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.