• Stars
    star
    324
  • Rank 129,708 (Top 3 %)
  • Language
    Objective-C
  • License
    Other
  • Created about 12 years ago
  • Updated almost 11 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.

Purpose

ViewUtils is a collection of category methods that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with. ViewUtils covers:

  • Nib loading - makes it easy to load views from nibs without a UIViewController
  • Layout - set and get position and width/height properties individually
  • Searching - retrieve subviews based on class, tag or arbitrary predicates
  • Responder - find the first responder within a given view

Supported OS & SDK Versions

  • Supported build target - iOS 7.0 / Mac OS 10.9 (Xcode 5.0, Apple LLVM compiler 5.0)
  • Earliest supported deployment target - iOS 6.0 / Mac OS 10.7
  • Earliest compatible deployment target - iOS 4.3 / Mac OS 10.6

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this iOS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

ARC Compatibility

ViewUtils works with both ARC and non-ARC projects. There is no need to exclude ViewUtils files from the ARC validation process, or to convert ViewUtils using the ARC conversion tool.

Thread Safety

UIView is inherently single-threaded, so ViewUtils methods should only be used on the main thread.

Installation

To use the ViewUtils categories in an app, just drag the ViewUtils.h and .m files (demo files and assets are not needed) into your project and import the header file into any class where you wish to make use of the ViewUtils functionality, or include it in your prefix.pch file to make it available globally within your project.

Extension Methods

ViewUtils extends UIView with the following methods:

+ (id)instanceWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)bundleOrNil owner:(id)owner;

This method loads a view from a nib file. The view to be loaded must be the first object in the file. This method is useful for loading views such as UITableViewCells, or iCarousel item views. The nib file is cached, so subequent loads will perform better.

- (void)loadContentsWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)bundleOrNil;

This method is similar to instanceWithNibName:, but instead of returning the first view in the nib file, this method loads that view and then adds it as a subview to the view on which the method is called, resizing the loaded view to fit the bounds of the superview if neccesary. This is especially useful if you want to create a complex view composed of reusable subviews, each stored in their own nib file.

- (UIView *)viewMatchingPredicate:(NSPredicate *)predicate;

Returns either the view itself of the first subview that matches the specified predicate. If no subview matches, the method returns nil.

- (UIView *)viewWithTag:(NSInteger)tag ofClass:(Class)viewClass;

Returns either the view itself of the first subview that has the specified tag value, and is of the specified class. This is safer than the regular viewWithTag: method.

- (UIView *)viewOfClass:(Class)viewClass;

Returns either the view itself of the first subview of the specified class.

- (NSArray *)viewsMatchingPredicate:(NSPredicate *)predicate;
- (NSArray *)viewsWithTag:(NSInteger)tag;
- (NSArray *)viewsWithTag:(NSInteger)tag ofClass:(Class)viewClass;
- (NSArray *)viewsOfClass:(Class)viewClass;

These methods work exactly like their single-view equivalents, but instead of returning the first view that matches, they return all views that match. The search is performed in a depth-first fashion.

- (UIView *)firstSuperviewMatchingPredicate:(NSPredicate *)predicate;
- (UIView *)firstSuperviewOfClass:(Class)viewClass;
- (UIView *)firstSuperviewWithTag:(NSInteger)tag;
- (UIView *)firstSuperviewWithTag:(NSInteger)tag ofClass:(Class)viewClass;

These methods work like the viewMatching/Of/Width versions, but work up the view hierarchy instead of down and will return the first parent view that matches the specified criteria.

- (BOOL)viewOrAnySuperviewMatchesPredicate:(NSPredicate *)predicate;
- (BOOL)viewOrAnySuperviewIsKindOfClass:(Class)viewClass;

This method returns YES if the view, or any superview in in the chain matches the criteria. This is useful for event handling, for example if you'd like to know if a given touch was either on or within a given control or control type, e.g. so you can ignore gestures performed on specific views.

- (BOOL)isSuperviewOfView:(UIView *)view;
- (BOOL)isSubviewOfView:(UIView *)view;

These methods allow you to determine if a view is a child of another view. These methods will search the entire superview chain, not just a single level, so if one view is the superview of the superview of the other one, it will still return YES.

- (UIViewController *)firstViewController;

This method uses the responder chain to identify the first view controller in the controller chain that is responsible for the view. So for example, if this method is called on a button, it will return the view controller that hosts the view that contains that button.

- (UIView *)firstResponder;

This method returns the first responder if it is a subview of the view on which the method is called, or nil if not. If you don't know which subview tree the first responder might be located in, calling this method on the main window or the root view of the current frontmost view controller should return the desired result.

- (void)setLeft:(CGFloat)left right:(CGFloat)right;
- (void)setWidth:(CGFloat)width right:(CGFloat)right;
- (void)setTop:(CGFloat)top bottom:(CGFloat)bottom;
- (void)setHeight:(CGFloat)height bottom:(CGFloat)bottom;

It's often fiddly to set both the left and right edges of a view, or set the width without affecting the right-hand edge because the properties are linked. These setter methods make it a little easier to do this by allowing you to set both properties with a single method call.

- (void)crossfadeWithDuration:(NSTimeInterval)duration;
- (void)crossfadeWithDuration:(NSTimeInterval)duration completion:(void (^)(void))completion;

These methods use Core Animation to perform a crossfade transition of the specified duration. A crossfade is often useful if you want to animate the change of some view property that does not already support animation. A typical example would be changing the text in a UILabel or the image in a UIImageView.

Extension Properties

ViewUtils extends UIView with the following properties for setting the frame position and dimensions:

@property (nonatomic, assign) CGPoint origin;

The position within the superview of the view origin (the top-left corner). This is equivalent to view.frame.origin.

@property (nonatomic, assign) CGSize size;

The outer dimensions of the view. This is equivalent to view.frame.size.

@property (nonatomic, assign) CGFloat top;
@property (nonatomic, assign) CGFloat left;
@property (nonatomic, assign) CGFloat bottom;
@property (nonatomic, assign) CGFloat right;

The positions of the four corners of the view within the superview. These positions are all relative to the top-left corner of the superview, so (for example) the view.bottom property is equivalent to view.top + view.height.

@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;

The outer dimensions of the view. These are equivalent to view.size.width and view.size.height respectively.

@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;

The position of the anchor point for the view (typically the center) within the superview. These are equivqlent to view.center.x and view.center.y respectively.

@property (nonatomic, assign) CGSize boundsSize;
@property (nonatomic, assign) CGFloat boundsWidth;
@property (nonatomic, assign) CGFloat boundsHeight;

The dimensions of the view bounds (the inner size). The bounds size is useful when the view has been transformed and you can no longer rely on the frame size to get or set the content dimensions accurately.

@property (nonatomic, readonly) CGRect contentBounds;

Quite often you wish to position a subview to exactly fill its superview, but in order to do that you must contruct a CGRect with the width and height of the superview's bounds and an origin of 0,0. Unfortunately there is no guarantee that the superview.bounds will have an origin of 0,0 because in a UIWindow that has been rotated, or a UIScrollView that has been scrolled or zoomed, the bounds origin will have been changed in order to correctly align the contents within the view frame. The contentBounds property returns a rect that matches the bounds size, but always has an origin of 0,0.

@property (nonatomic, readonly) CGPoint contentCenter;

Quite often you wish to position a subview in the exact center of its superview, but calculating the center of a view is a tedious piece of code to write. The contentCenter property returns this position.

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,068
star
13

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
14

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
15

AsyncImageView

[DEPRECATED]
Objective-C
906
star
16

iConsole

[DEPRECATED]
Objective-C
859
star
17

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
18

FXLabel

[DEPRECATED]
Objective-C
816
star
19

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
20

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
21

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
22

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
23

Base64

[DEPRECATED]
Objective-C
578
star
24

FXKeychain

[DEPRECATED]
Objective-C
554
star
25

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
26

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
27

GLView

[DEPRECATED]
Objective-C
477
star
28

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
29

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
30

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
31

VectorMath

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics
Swift
367
star
32

ReflectionView

[DEPRECATED]
Objective-C
359
star
33

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
34

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
35

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
36

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
37

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
38

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
39

ColorUtils

[DEPRECATED]
Objective-C
256
star
40

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
41

OSNavigationController

[DEPRECATED]
Objective-C
233
star
42

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
43

iNotify

[DEPRECATED]
Objective-C
225
star
44

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
45

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
46

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
47

RequestQueue

[DEPRECATED]
Objective-C
174
star
48

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
49

Sprinter

A library for formatting strings on iOS and macOS
Swift
166
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star