intrinsiccontentsizeloadview什么时候调用用

本文内容来自
The NSLayoutAnchor class is a factory class for creating NSLayoutConstraint objects using a fluent API.
NSLayoutAnchor是用来创建NSLayoutConstraint对象的工厂类。相对于原来创建约束的方法更简便。
// Creating constraints using NSLayoutConstraint
NSLayoutConstraint(item: subview,
attribute: .Leading,
relatedBy: .Equal,
toItem: view,
attribute: .LeadingMargin,
multiplier: 1.0,
constant: 0.0).active = true
NSLayoutConstraint(item: subview,
attribute: .Trailing,
relatedBy: .Equal,
toItem: view,
attribute: .TrailingMargin,
multiplier: 1.0,
constant: 0.0).active = true
// Creating the same constraints using Layout Anchors
let margins = view.layoutMarginsGuide
subview.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
NSLayoutAnchor有三个子类:
NSLayoutXAxisAnchor
NSLayoutYAxisAnchor
NSLayoutDimension
例如,如下创建的约束:
bookTextView.translatesAutoresizingMaskIntoConstraints = false
bookTextView.leadingAnchor.constraintEqualToAnchor(
view.leadingAnchor).active = true
bookTextView.trailingAnchor.constraintEqualToAnchor(
view.trailingAnchor).active = true
bookTextView.bottomAnchor.constraintEqualToAnchor(
view.bottomAnchor,
constant: -20).active = true
bookTextView.heightAnchor.constraintEqualToAnchor(
view.heightAnchor,
active设置为true,表示其马上生效。
View Layout Margins
所有的view都有一个layoutMarginsGuide属性。相对于View Layout Margins创建的约束,在其view的边缘会留下一些空白的距离。
avatarView.translatesAutoresizingMaskIntoConstraints = false
avatarView.topAnchor.constraintEqualToAnchor(
view.topAnchor).active = true
avatarView.leadingAnchor.constraintEqualToAnchor(
view.layoutMarginsGuide.leadingAnchor).active = true
avatarView.trailingAnchor.constraintEqualToAnchor(
view.layoutMarginsGuide.trailingAnchor).active = true
avatarView.heightAnchor.constraintEqualToConstant(200).active = true
如下,avatarView在左右两侧会留下空白的距离:
View Controller Layout Guides
同view一样,view controller 都有一个top和bottom的layout guide。
上图中,avatarView在状态栏的底部,但如果还有其他的透明的bars,例如导航栏和底部的tab bar,那么上面的avatarView,就会被遮挡住。
所以当给view controller的view的subviews,添加约束时,要约束到view controller的top guide的 bottom和bottom guide的top anchor
avatarView.topAnchor.constraintEqualToAnchor(
topLayoutGuide.bottomAnchor).active = true
bookTextView.bottomAnchor.constraintEqualToAnchor(
bottomLayoutGuide.topAnchor,
constant: -20).active = true
效果如下:
Readable Content Guide
上图中绿色的bookTextView,当前左右边缘对齐到屏幕的边缘,这样在iPad上显示时,非常不便于阅读。
使用 readable content guides,会根据size class来调整大小,这样会在边缘添加空白的距离,来跟适合阅读。
bookTextView.leadingAnchor.constraintEqualToAnchor(
view.readableContentGuide.leadingAnchor).active = true
bookTextView.trailingAnchor.constraintEqualToAnchor(
view.readableContentGuide.trailingAnchor).active = true
在iPad横屏下,显示如下:
Intrinsic Content Size
所有的view都有一个intrinsic content size, 如果设置了content size,就不用创建width 和 height 约束。
UILabel的Intrinsic Content Size由font和text决定
UIView默认的Intrinsic Content Size是UIViewNoIntrinsicMetric,表示的是没有大小。
设置AvatarView的UIViewNoIntrinsicMetric
override func intrinsicContentSize() -& CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: 100)
如果想要在app运行时改变 intrinsic content size,可以调用invalidateIntrinsicContentSize()方法来更新
设置ContentHuggingPriority和ContentCompressionResistancePriority
setContentHuggingPriority(_:forAxis:) takes a priority and an axis to determine how much a view wants to stretch. A high priority means that a view wants to stay the same size. A low priority allows the view to stretch.
setContentCompressionResistancePriority(_:forAxis:) also takes a priority and an axis. This method determines how much a view wants to shrink. A high priority means that a view tries not to shrink and a low priority means that the view can squish.
优先级大小在1到1000之间,1000是最高的,标准的优先值如下:
UILayoutPriorityRequired = 1000
UILayoutPriorityDefaultHigh = 750
UILayoutPriorityDefaultLow = 250
给chapterLabel设置优先级:
chapterLabel.setContentHuggingPriority(
UILayoutPriorityRequired,
forAxis: .Vertical)
chapterLabel.setContentCompressionResistancePriority(
UILayoutPriorityRequired,
forAxis: .Vertical)
这样保证其不会被拉伸和压缩
Constraint Activation and Deactivation
根据不同的size class来active约束
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.horizontalSizeClass == .Regular {
NSLayoutConstraint.deactivateConstraints(compactConstraints)
NSLayoutConstraint.activateConstraints(regularConstraints)
socialMediaView.axis = .Horizontal
NSLayoutConstraint.deactivateConstraints(regularConstraints)
NSLayoutConstraint.activateConstraints(compactConstraints)
socialMediaView.axis = .Vertical
traitCollectionDidChange(_:)方法会捕获trait collection的改变
更新Constraint
所有的约束在updateConstraints()中被计算。This is where all priorities, compression resistance, hugging and intrinsic content size all come together in one complex algorithm.可以重写此方法来改变约束。
Views are then laid out in layoutSubviews(). If you need to access the correct view frame, you can override this.
override func updateConstraints() {
super.updateConstraints()
var aspectRatio: CGFloat = 1
if let image = image {
aspectRatio = image.size.width / image.size.height
aspectRatioConstraint?.active = false
aspectRatioConstraint =
imageView.widthAnchor.constraintEqualToAnchor(
imageView.heightAnchor,
multiplier: aspectRatio)
aspectRatioConstraint?.active = true
手工布局view
Occasionally you’ll want to access a view’s frame. This can only safely be done in layoutSubviews() after all the views have been laid out by the Auto Layout engine.
override func layoutSubviews() {
super.layoutSubviews()
if bounds.height & socialMediaView.bounds.height {
socialMediaView.alpha = 0
socialMediaView.alpha = 1
if imageView.bounds.height & 30 {
imageView.alpha = 0
imageView.alpha = 1
本文已收录于以下专栏:
相关文章推荐
本文内容来自Easier Auto Layout: Coding Constraints in iOS 9创建约束
The NSLayoutAnchor class is a factory cl...
原理:IOS6.0 之后,苹果优化了UI界面的布局方式,提出了自动布局的概念,和之前的autoresizing相比功能更强大。子视图基于父视图的自动布局显示。都是父视图去添加对子视图的约束。
  在这...
对于机器学习,很多人的观点是:机器学习技术是今后所有技术人员都绕不过的一个门槛。 那么,普通程序员该学习机器学作为一名对机器学习心有向往的程序员,我该以什么样的姿势开始呢?
Autolayout经验分享
1、SQL 创建约束和主键约束那么约束的作用是什么呢?正所谓无规矩不成方圆,MSSQL也建立一套约束机制,比如说再创建字段或者修改字段的时候,限制其输入格式、范围抑或是执行某种检查,如果不想自己用代码...
约束的类型:
oracle数据库支持的约束类型包括:
1.unique 2.not null 3.primary key 4.foreignkey 5.check
约束都有名称。如果没有显示地给它们命...
约束,顾名思义是对表的一种限制,其作用为保证表的完整性,唯一性。mysql表约束和列约束包括以下5种(NOT NULL和DEFAULT只有列约束)
Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。Masonry是一个非常优秀的auto...
CHECK分为列约束和表约束,列约束是只对表中的某一个列进行的约束,可以在列的属性中进行设置,而表约束是对多个列进行的约束,需要在表的属性中进行设置(其实列约束也可以在表约束中设...
图书信息表:图书编号,图书名称,出版社,出版日期,图书价格,图书作者,借出标识,读者编号,描述
①主键 constraint pk_name primary key
②外键 constraint f...
使用sql语句创建和删除约束
主建约束:(primary key constraint);
唯一约束:(unique constraint);
检查约束:(check constra...
他的最新文章
讲师:唐宇迪
讲师:卿来云
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)iOS开发(13)
#import &Foundation/Foundation.h&
#import &UIKit/UIResponder.h&
#import &UIKit/UIInterface.h&
#import &UIKit/UIKitDefines.h&
#import &UIKit/UIAppearance.h&
#import &UIKit/UIDynamicBehavior.h&
#import &UIKit/NSLayoutConstraint.h&
#import &UIKit/UITraitCollection.h&
typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
UIViewAnimationCurveEaseInOut,
UIViewAnimationCurveEaseIn,
UIViewAnimationCurveEaseOut,
UIViewAnimationCurveLinear
typedef NS_ENUM(NSInteger, UIViewContentMode) {
UIViewContentModeScaleToFill, 缩放内容到合适比例大小
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,视图顶部对齐
UIViewContentModeBottom,视图底部对齐
UIViewContentModeLeft,视图左侧对齐
UIViewContentModeRight,视图右侧对齐
UIViewContentModeTopLeft,视图左上角对齐
UIViewContentModeTopRight, 视图右上角对齐
UIViewContentModeBottomLeft,视图左下角对齐
UIViewContentModeBottomRight,视图右下角对齐
typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
UIViewAnimationTransitionNone,
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone
UIViewAutoresizingFlexibleLeftMargin
UIViewAutoresizingFlexibleWidth
UIViewAutoresizingFlexibleRightMargin
UIViewAutoresizingFlexibleTopMargin
UIViewAutoresizingFlexibleHeight
UIViewAutoresizingFlexibleBottomMargin = 1 && 5
typedef NS_OPTIONS(NSUInteger, UIViewAnimationOptions) {
UIViewAnimationOptionLayoutSubviews
UIViewAnimationOptionAllowUserInteraction
UIViewAnimationOptionBeginFromCurrentState
UIViewAnimationOptionRepeat
UIViewAnimationOptionAutoreverse
UIViewAnimationOptionOverrideInheritedDuration = 1 &&
UIViewAnimationOptionOverrideInheritedCurve
UIViewAnimationOptionAllowAnimatedContent
UIViewAnimationOptionShowHideTransitionViews
UIViewAnimationOptionOverrideInheritedOptions
UIViewAnimationOptionCurveEaseInOut
= 0 && 16,
UIViewAnimationOptionCurveEaseIn
= 1 && 16,
UIViewAnimationOptionCurveEaseOut
= 2 && 16,
UIViewAnimationOptionCurveLinear
= 3 && 16,
UIViewAnimationOptionTransitionNone
= 0 && 20,
UIViewAnimationOptionTransitionFlipFromLeft
= 1 && 20,
UIViewAnimationOptionTransitionFlipFromRight
= 2 && 20,
UIViewAnimationOptionTransitionCurlUp
= 3 && 20,
UIViewAnimationOptionTransitionCurlDown
= 4 && 20,
UIViewAnimationOptionTransitionCrossDissolve
= 5 && 20,
UIViewAnimationOptionTransitionFlipFromTop
= 6 && 20,
UIViewAnimationOptionTransitionFlipFromBottom
= 7 && 20,
} NS_ENUM_AVAILABLE_IOS(4_0);
typedef NS_OPTIONS(NSUInteger, UIViewKeyframeAnimationOptions) {
UIViewKeyframeAnimationOptionLayoutSubviews
= UIViewAnimationOptionLayoutSubviews,
UIViewKeyframeAnimationOptionAllowUserInteraction
= UIViewAnimationOptionAllowUserInteraction,
UIViewKeyframeAnimationOptionBeginFromCurrentState
= UIViewAnimationOptionBeginFromCurrentState,
UIViewKeyframeAnimationOptionRepeat
= UIViewAnimationOptionRepeat,
UIViewKeyframeAnimationOptionAutoreverse
= UIViewAnimationOptionAutoreverse,
UIViewKeyframeAnimationOptionOverrideInheritedDuration = UIViewAnimationOptionOverrideInheritedDuration,
UIViewKeyframeAnimationOptionOverrideInheritedOptions
= UIViewAnimationOptionOverrideInheritedOptions,
UIViewKeyframeAnimationOptionCalculationModeLinear
= 0 && 10,
UIViewKeyframeAnimationOptionCalculationModeDiscrete
= 1 && 10,
UIViewKeyframeAnimationOptionCalculationModePaced
= 2 && 10,
UIViewKeyframeAnimationOptionCalculationModeCubic
= 3 && 10,
UIViewKeyframeAnimationOptionCalculationModeCubicPaced = 4 && 10
} NS_ENUM_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSUInteger, UISystemAnimation) {
UISystemAnimationDelete,
} NS_ENUM_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSInteger, UIViewTintAdjustmentMode) {
UIViewTintAdjustmentModeAutomatic,
UIViewTintAdjustmentModeNormal,
UIViewTintAdjustmentModeDimmed,
} NS_ENUM_AVAILABLE_IOS(7_0);
@protocol UICoordinateSpace &NSObject&
- (CGPoint)convertPoint:(CGPoint)point toCoordinateSpace:(id &UICoordinateSpace&)coordinateSpace NS_AVAILABLE_IOS(8_0);
- (CGPoint)convertPoint:(CGPoint)point fromCoordinateSpace:(id &UICoordinateSpace&)coordinateSpace NS_AVAILABLE_IOS(8_0);
- (CGRect)convertRect:(CGRect)rect toCoordinateSpace:(id &UICoordinateSpace&)coordinateSpace NS_AVAILABLE_IOS(8_0);
- (CGRect)convertRect:(CGRect)rect fromCoordinateSpace:(id &UICoordinateSpace&)coordinateSpace NS_AVAILABLE_IOS(8_0);
@property (readonly, nonatomic) CGRect bounds NS_AVAILABLE_IOS(8_0);
@class UIBezierPath, UIEvent, UIWindow, UIViewController, UIColor, UIGestureRecognizer, UIMotionEffect, CALayer;
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder &NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace& {
NSMutableArray *_gestureR
*_subviewC
UIViewController *_viewD
*_backgroundColorSystemColorN
NSUInteger
_countOfMotionEffectsInS
unsigned int userInteractionDisabled:1;
unsigned int implementsDrawRect:1;
unsigned int implementsDidScroll:1;
unsigned int implementsMouseTracking:1;
unsigned int implementsIntrinsicContentSize:1;
unsigned int hasBackgroundColor:1;
unsigned int isOpaque:1;
unsigned int becomeFirstResponderWhenCapable:1;
unsigned int interceptMouseEvent:1;
unsigned int deallocating:1;
unsigned int debugFlash:1;
unsigned int debugSkippedSetNeedsDisplay:1;
unsigned int debugScheduledDisplayIsRequired:1;
unsigned int isInAWindow:1;
unsigned int isAncestorOfFirstResponder:1;
unsigned int dontAutoresizeSubviews:1;
unsigned int autoresizeMask:6;
unsigned int patternBackground:1;
unsigned int fixedBackgroundPattern:1;
unsigned int dontAnimate:1;
unsigned int superLayerIsView:1;
unsigned int layerKitPatternDrawing:1;
unsigned int multipleTouchEnabled:1;
unsigned int exclusiveTouch:1;
unsigned int hasViewController:1;
unsigned int needsDidAppearOrDisappear:1;
unsigned int gesturesEnabled:1;
unsigned int deliversTouchesForGesturesToSuperview:1;
unsigned int chargeEnabled:1;
unsigned int skipsSubviewEnumeration:1;
unsigned int needsDisplayOnBoundsChange:1;
unsigned int hasTiledLayer:1;
unsigned int hasLargeContent:1;
unsigned int unused:1;
unsigned int traversalMark:1;
unsigned int appearanceIsInvalid:1;
unsigned int monitorsSubtree:1;
unsigned int hostsAutolayoutEngine:1;
unsigned int constraintsAreClean:1;
unsigned int subviewLayoutConstraintsAreClean:1;
unsigned int intrinsicContentSizeConstraintsAreClean:1;
unsigned int potentiallyHasDanglyConstraints:1;
unsigned int doesNotTranslateAutoresizingMaskIntoConstraints:1;
unsigned int autolayoutIsClean:1;
unsigned int layoutFlushingDisabled:1;
unsigned int layingOutFromConstraints:1;
unsigned int wantsAutolayout:1;
unsigned int subviewWantsAutolayout:1;
unsigned int isApplyingValuesFromEngine:1;
unsigned int isInAutolayout:1;
unsigned int isSubviewUpdatingAutoresizingConstraints:1;
unsigned int isUpdatingConstraints:1;
unsigned int isHostingUpdateConstraintsPassDuringLayout:1;
unsigned int isRunningEngineLevelConstraintsPass:1;
unsigned int isUnsatisfiableConstraintsLoggingSuspended:1;
unsigned int systemLayoutFittingSizeNeedsUpdate:1;
unsigned int systemLayoutFittingSizeNeedsUpdateInWholeSubtree:1;
unsigned int isCalculatingSystemLayoutFittingSize:1;
unsigned int stayHiddenAwaitingReuse:1;
unsigned int stayHiddenAfterReuse:1;
unsigned int skippedLayoutWhileHiddenForReuse:1;
unsigned int hasMaskView:1;
unsigned int hasVisualAltitude:1;
unsigned int hasBackdropMaskViews:1;
unsigned int backdropMaskViewFlags:5;
unsigned int delaysTouchesForSystemGestures:1;
unsigned int subclassShouldDelayTouchForSystemGestures:1;
unsigned int hasMotionEffects:1;
unsigned int backdropOverlayMode:2;
unsigned int tintAdjustmentMode:2;
unsigned int isReferenceView:1;
unsigned int focusState:2;
unsigned int hasUserInterfaceIdiom:1;
unsigned int userInterfaceIdiom:3;
unsigned int ancestorDefinesTintColor:1;
unsigned int ancestorDefinesTintAdjustmentMode:1;
unsigned int needsTraitCollectionDidChange:1;
unsigned int coloredViewBounds:1;
unsigned int coloredAlignmentRects:1;
unsigned int preservesSuperviewMargins:1;
unsigned int hasGeometryObservers:1;
unsigned int wantsGeometryChanges:1;
+ (Class)layerC
- (instancetype)initWithFrame:(CGRect)
@property(nonatomic,getter=isUserInteractionEnabled) BOOL userInteractionE
@property(nonatomic)
@property(nonatomic,readonly,retain)
@interface UIView(UIViewGeometry)
@property(nonatomic) CGRect
@property(nonatomic) CGRect
@property(nonatomic) CGPoint
@property(nonatomic) CGAffineT
@property(nonatomic) CGFloat
contentScaleFactor NS_AVAILABLE_IOS(4_0);
@property(nonatomic,getter=isMultipleTouchEnabled) BOOL multipleTouchE
@property(nonatomic,getter=isExclusiveTouch) BOOL
exclusiveT
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)
==========*******convertPonit****===================
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)
CGPoint pointInView =
[self.redView convertPoint:pointInOriView fromView:self.view];
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)
例把UITableViewCell中的subview(btn)的frame转换到 controllerA中
CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];
CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];
或当已知btn时:
CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];
CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];
=================***************==========================
@property(nonatomic) BOOL
autoresizesS
@property(nonatomic) UIViewAutoresizing autoresizingM
- (CGSize)sizeThatFits:(CGSize)
- (void)sizeToF
@interface UIView(UIViewHierarchy)
@property(nonatomic,readonly) UIView
@property(nonatomic,readonly,copy) NSArray *
@property(nonatomic,readonly) UIWindow
- (void)removeFromS
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingS
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingS
- (void)bringSubviewToFront:(UIView *)
- (void)sendSubviewToBack:(UIView *)
- (void)didAddSubview:(UIView *)
- (void)willRemoveSubview:(UIView *)
- (void)willMoveToSuperview:(UIView *)newS
- (void)didMoveToS
- (void)willMoveToWindow:(UIWindow *)newW
- (void)didMoveToW
- (BOOL)isDescendantOfView:(UIView *)
- (UIView *)viewWithTag:(NSInteger)
- (void)setNeedsL
- (void)layoutIfN
- (void)layoutS
layoutSubviews在以下情况下会被调用:
1、init初始化不会触发layoutSubviews ,
但 initWithFrame 进行初始化时,当rect的值不为CGRectZero时,也会触发.
2、addSubview会触发layoutSubviews.
3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化.
4、滚动一个UIScrollView会触发layoutSubviews.
5、旋转Screen会触发父UIView上的layoutSubviews事件.
6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件.
[1]、layoutSubviews对subviews重新布局
[2]、layoutSubviews方法调用先于drawRect
[3]、setNeedsLayout在receiver标上一个需要被重新布局的标记,在系统runloop的下一个周期自动调用layoutSubviews
[4]、layoutIfNeeded方法如其名,UIKit会判断该receiver是否需要layout
[5]、layoutIfNeeded遍历的不是superview链,应该是subviews链
@property (nonatomic) UIEdgeInsets layoutMargins NS_AVAILABLE_IOS(8_0);
@property (nonatomic) BOOL preservesSuperviewLayoutMargins NS_AVAILABLE_IOS(8_0);
- (void)layoutMarginsDidChange NS_AVAILABLE_IOS(8_0);
@interface UIView(UIViewRendering)
drawRect是对receiver的重绘
setNeedDisplay在receiver标上一个需要被重新绘图的标记,在下一个draw周期自动重绘,iphone device的刷新频率是60hz,也就是1/60秒后重绘
- (void)drawRect:(CGRect)
- (void)setNeedsD
- (void)setNeedsDisplayInRect:(CGRect)
@property(nonatomic)
@property(nonatomic,copy)
*backgroundColor UI_APPEARANCE_SELECTOR;
@property(nonatomic)
决定该消息接收者(UIView instance)是否让其视图不透明,用处在于给绘图系统提供一个性能优化开关。
insertDemoTwo.opaque = NO;
该值为YES, 那么绘图在绘制该视图的时候把整个视图当作不透明对待。优化绘图过程并提升系统性能;为了性能方面的考量,默认被置为YES。
该值为NO,,不去做优化操作。
一个不透明视图需要整个边界里面的内容都是不透明。基于这个原因,opaque设置为YES,要求对应的alpha必须为1.0。如果一个UIView实例opaque被设置为YES, 而同时它又没有完全填充它的边界(bounds),或者它包含了整个或部分的透明的内容视图,那么将会导致未知的结果。
因此,如果视图部分或全部支持透明,那么你必须把opaque这个值设置为NO.
@property(nonatomic,getter=isOpaque) BOOL
insertDemoOne.clearsContextBeforeDrawing = YES;
提高描画性能(特别是在滚动过程)的另一个方法是将视图的clearsContextBeforeDrawing属性设置为NO。当这个属性被设置为YES时,UIKIt会在调用drawRect:方法之前,把即将被该方法更新的区域填充为透明的黑色。将这个属性设置为NO可以取消相应的填充操作,而由应用程序负责完全重画传给drawRect:方法的更新矩形中的部。这样的优化在滚动过程中通常是一个好的折衷。
@property(nonatomic)
clearsContextBeforeD
@property(nonatomic,getter=isHidden) BOOL
@property(nonatomic)
UIViewContentMode
[imageDemo setContentStretch:CGRectMake(50.0/100.0, 75.0/150.0, 10.0/100.0, 10.0/150.0)];
当demo.png大于imageDemo的大小时,就缩小。
当demo.png小于imageDemo的大小时,就放大。
@property(nonatomic)
contentStretch NS_DEPRECATED_IOS(3_0,6_0);
@property(nonatomic,retain)
*maskView NS_AVAILABLE_IOS(8_0);
@property(nonatomic,retain) UIColor *tintColor NS_AVAILABLE_IOS(7_0);
@property(nonatomic) UIViewTintAdjustmentMode tintAdjustmentMode NS_AVAILABLE_IOS(7_0);
- (void)tintColorDidChange NS_AVAILABLE_IOS(7_0);
@interface UIView(UIViewAnimation)
+ (void)beginAnimations:(NSString *)animationID context:(void *)
+ (void)commitA
+ (void)setAnimationDelegate:(id)
+ (void)setAnimationWillStartSelector:(SEL)
+ (void)setAnimationDidStopSelector:(SEL)
+ (void)setAnimationDuration:(NSTimeInterval)
+ (void)setAnimationDelay:(NSTimeInterval)
+ (void)setAnimationStartDate:(NSDate *)startD
+ (void)setAnimationCurve:(UIViewAnimationCurve)
+ (void)setAnimationRepeatCount:(float)repeatC
+ (void)setAnimationRepeatAutoreverses:(BOOL)repeatA
+ (void)setAnimationBeginsFromCurrentState:(BOOL)fromCurrentS
如果是YES,那么在开始和结束图片视图渲染一次并在动画中创建帧;否则,视图将会在每一帧都渲染。例如缓存,你不需要在视图转变中不停的更新,你只需要等到转换完成再去更新视图。
1、开始一个动画块。
2、在容器视图中设置转换。
3、在容器视图中移除子视图。
4、在容器视图中添加子视图。
5、结束动画块。
+ (void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)
+ (void)setAnimationsEnabled:(BOOL)
+ (BOOL)areAnimationsE
+ (void)performWithoutAnimation:(void (^)(void))actionsWithoutAnimation NS_AVAILABLE_IOS(7_0);
@interface UIView(UIViewAnimationWithBlocks)
transform alpha backgroundColor contentStretch
completion完成后需要做的操作
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(4_0);
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(4_0);
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_AVAILABLE_IOS(4_0);
参考 http:
initialSpringVelocity 表示初始速度,数值越大一开始移动越快
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);
duration:2.0
options:UIViewAnimationOptionTransitionCurlDown
animations:^{
[_blackView removeFromSuperview];
[_redView addSubview:_blackView];
} completion:^(BOOL finished) {
_redView.backgroundColor = [UIColor brownColor];
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(4_0);
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(4_0);
+ (void)performSystemAnimation:(UISystemAnimation)animation onViews:(NSArray *)views options:(UIViewAnimationOptions)options animations:(void (^)(void))parallelAnimations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);
@interface UIView (UIViewKeyframeAnimations)
***********
[UIViewanimateKeyframesWithDuration:2.0delay:0options:UIViewKeyframeAnimationOptionRepeatanimations:^{
_blackView.frame = CGRectMake(30, 30, 50, 50);
[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0 animations:^{
_redView.frame = CGRectMake(50, 50, 50, 50);
} completion:^(BOOL finished) {
_redView.frame= CGRectMake(50, 50, 100, 100);;
_blackView.frame = CGRectMake(30, 30, 80, 80);
+ (void)animateKeyframesWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);
frameDuration是指动画持续时间
+ (void)addKeyframeWithRelativeStartTime:(double)frameStartTime relativeDuration:(double)frameDuration animations:(void (^)(void))animations NS_AVAILABLE_IOS(7_0);
@interface UIView (UIViewGestureRecognizers)
@property(nonatomic,copy) NSArray *gestureRecognizers NS_AVAILABLE_IOS(3_2);
UIKit 中UIGestureRecognizer类的子类系列如下:
UITapGestureRecognizer – “轻击”手势。可以配置为“单击”和“连击”的识别。
UIPinchGestureRecognizer –“捏合”手势。该手势通常用于缩放视图或改变可视组件的大小。
UIPanGestureRecognizer – “平移”手势。识别拖拽或移动动作。
UISwipeGestureRecognizer – “轻扫”手势。当用户从屏幕上划过时识别为该手势。可以指定该动作的方向(上、下、左、右)。
UIRotationGestureRecognizer – “转动”手势。用户两指在屏幕上做相对环形运动。
UILongPressGestureRecognizer – “长按”手势。使用1指或多指触摸屏幕并保持一定时间。
- (void)addGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer NS_AVAILABLE_IOS(3_2);
- (void)removeGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer NS_AVAILABLE_IOS(3_2);
手势识别处理方式在gesture recognizer视图转出《UIGestureRecognizerStatePossible》状态时调用,
如果返回NO,则转换到《UIGestureRecognizerStateFailed》;
如果返回YES,则继续识别触摸序列.(默认情况下为YES)。
[insertDemoOne gestureRecognizerShouldBegin:demoGesture];
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer NS_AVAILABLE_IOS(6_0);
@interface UIView (UIViewMotionEffects)
当你打开装有iOS7以上的iPhone主屏,默认的背景是一幅蓝色的星空图片。当上下左右翻转iPhone时,有趣的效果将会出现,星空背景也会沿着各个方向发生位移,这与主屏上的各个App Icon形成了一种独特的视差效果。
1. UIInterpolatingMotionEffect
UIInterpolatingMotionEffect是UIMotionEffect的子类,虽然扩展也不复杂,提供的方法也很简单,但在很多场景下可以比较直接和方便的满足我们的需求。
它有4个property:
1.keyPath,左右翻转屏幕将要影响到的属性,比如center.x。
2.type(UIInterpolatingMotionEffectType类型),观察者视角,也就是屏幕倾斜的方式,目前区分水平和垂直两种方式。
3&4.minimumRelativeValue和maximumRelativeValue,keyPath对应的值的变化范围,注意这个是id类型。min对应最小的offset,max对应最大的offset。
UIInterpolatingMotionEffect * xEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
xEffect.minimumRelativeValue =
[NSNumber numberWithFloat:-40.0];
xEffect.maximumRelativeValue = [NSNumber numberWithFloat:40.0];
[targetView addMotionEffect:xEffect];
参考自http:
- (void)addMotionEffect:(UIMotionEffect *)effect NS_AVAILABLE_IOS(7_0);
- (void)removeMotionEffect:(UIMotionEffect *)effect NS_AVAILABLE_IOS(7_0);
@property (copy, nonatomic) NSArray *motionEffects NS_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSInteger, UILayoutConstraintAxis) {
UILayoutConstraintAxisHorizontal = 0,
UILayoutConstraintAxisVertical = 1
@interface UIView (UIConstraintBasedLayoutInstallingConstraints)
- (NSArray *)constraints NS_AVAILABLE_IOS(6_0);
- (void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0);
- (void)addConstraints:(NSArray *)constraints NS_AVAILABLE_IOS(6_0);
- (void)removeConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0);
- (void)removeConstraints:(NSArray *)constraints NS_AVAILABLE_IOS(6_0);
@interface UIView (UIConstraintBasedLayoutCoreMethods)
- (void)updateConstraintsIfNeeded NS_AVAILABLE_IOS(6_0);
- (void)updateConstraints NS_AVAILABLE_IOS(6_0);
- (BOOL)needsUpdateConstraints NS_AVAILABLE_IOS(6_0);
- (void)setNeedsUpdateConstraints NS_AVAILABLE_IOS(6_0);
@interface UIView (UIConstraintBasedCompatibility)
- (BOOL)translatesAutoresizingMaskIntoConstraints NS_AVAILABLE_IOS(6_0);
- (void)setTranslatesAutoresizingMaskIntoConstraints:(BOOL)flag NS_AVAILABLE_IOS(6_0);
+ (BOOL)requiresConstraintBasedLayout NS_AVAILABLE_IOS(6_0);
@interface UIView (UIConstraintBasedLayoutLayering)
我们可以简单的对当前View设置用来布局的矩形,比如:
我们有一个自定义icon类型的Button,但是icon的大小比我们期望点击的Button区域要小。这个时候我们可以重写alignmentRectInsets,把icon放在适当的位置。
大多数情况下重写alignmentRectInsets这个方法可以满足我们的工作。如果需要更加个性化的修改,我们可以重写alignmentRectForFrame和frameForAlignmentRect这两个方法。比如我们不想减去视图固定的Insets,而是需要基于当前frame修改alignment rect。在重写这两个方法时,我们应该确保是互为可逆的。
- (CGRect)alignmentRectForFrame:(CGRect)frame NS_AVAILABLE_IOS(6_0);
- (CGRect)frameForAlignmentRect:(CGRect)alignmentRect NS_AVAILABLE_IOS(6_0);
- (UIEdgeInsets)alignmentRectInsets NS_AVAILABLE_IOS(6_0);
- (UIView *)viewForBaselineLayout NS_AVAILABLE_IOS(6_0);
UIKIT_EXTERN const CGFloat UIViewNoIntrinsicMetric NS_AVAILABLE_IOS(6_0);
- (CGSize)intrinsicContentSize
CGSize size = [label intrinsicContentSize];
if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
size.width += 4.0f;
size.width += 40.0f;
if (self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact) {
size.height += 4.0;
size.height += 40.0;
- (CGSize)intrinsicContentSize NS_AVAILABLE_IOS(6_0);
label.text = @"content update"
[self invalidateIntrinsicContentSize];
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
[super traitCollectionDidChange:previousTraitCollection];
if ((self.traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass)
|| (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass)) {
[self invalidateIntrinsicContentSize];
- (void)invalidateIntrinsicContentSize NS_AVAILABLE_IOS(6_0);
- (UILayoutPriority)contentHuggingPriorityForAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
- (UILayoutPriority)contentCompressionResistancePriorityForAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
上面最后四个API主要是通过修改水平或者垂直方向的优先级来实现视图是基于水平缩小(放大)还是垂直缩小(放大)。当我们的视图需要根据内部内容进行调整大小时,我们应该使用上述方法为当前视图设置初始值。而不应该重写这几个方法。
UIKIT_EXTERN const CGSize UILayoutFittingCompressedSize NS_AVAILABLE_IOS(6_0);
UIKIT_EXTERN const CGSize UILayoutFittingExpandedSize NS_AVAILABLE_IOS(6_0);
@interface UIView (UIConstraintBasedLayoutFittingSize)
下面这两个API可以获得当前使用AutoLayout视图的size。其中targetSize可以传入UILayoutFittingCompressedSize(最小情况下可能的Size)或者UILayoutFittingExpandedSize(最大情况下可能的Size)
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0);
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority NS_AVAILABLE_IOS(8_0);
@interface UIView (UIConstraintBasedLayoutDebugging)
- (NSArray *)constraintsAffectingLayoutForAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
- (BOOL)hasAmbiguousLayout NS_AVAILABLE_IOS(6_0);
- (void)exerciseAmbiguityInLayout NS_AVAILABLE_IOS(6_0);
我们应该让上面的四个方法只在DEBUG环境下被调用。
@interface UIView (UIStateRestoration)
@property (nonatomic, copy) NSString *restorationIdentifier NS_AVAILABLE_IOS(6_0);
- (void) encodeRestorableStateWithCoder:(NSCoder *)coder NS_AVAILABLE_IOS(6_0);
- (void) decodeRestorableStateWithCoder:(NSCoder *)coder NS_AVAILABLE_IOS(6_0);
@interface UIView (UISnapshotting)
毕竟用原始的view做动画代价太高.因为是截取了已经存在的内容,这个方法只能反应出这个被截取的view当前的状态信息,而不能反应这个被截取的view以后要显示的信息.然而,不管怎么样,调用这个方法都会比将view做成截图来加载效率更高.
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates NS_AVAILABLE_IOS(7_0);
- (UIView *)resizableSnapshotViewFromRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates withCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(7_0);
- (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates NS_AVAILABLE_IOS(7_0);
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4871次
排名:千里之外
(2)(1)(1)(1)(3)(1)(2)(5)(1)
(window.slotbydup = window.slotbydup || []).push({
id: '4740881',
container: s,
size: '200,200',
display: 'inlay-fix'}

我要回帖

更多关于 intrinsiccontentsize 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信