您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS:UIView 實例方法篇(Instance Methods)

編輯:iOS 開發綜合

承接上篇,本篇探索 UIView 的實例方法,並依功能分類整理。

初始化與編輯狀態

- (id)initWithFrame:(CGRect)aRect   // 以指定 frame 初始化視圖
- (BOOL)endEditing:(BOOL)force       // 結束編輯狀態,彈回鍵盤時特別有用

手勢與運動效果

- (void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer;
- (void)removeGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer;
- (void)addMotionEffect:(UIMotionEffect *)effect; // 加入運動效果,iOS 7 起使用

管理視圖層次

- (void)addSubview:(UIView *)view;
- (void)removeFromSuperview;
- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (BOOL)isDescendantOfView:(UIView *)view;

調整大小與布局

- (void)sizeToFit;                       // 自適應子視圖大小
- (CGSize)sizeThatFits:(CGSize)size;     // 回傳最適合子視圖的 size
- (void)layoutSubviews;                  // 佈局子視圖
- (void)layoutIfNeeded;                  // 立即佈局
- (void)setNeedsLayout;                  // 標記下一週期重新佈局

基於約束的布局(Constraint-Based Layout)

- (void)setTranslatesAutoresizingMaskIntoConstraints:(BOOL)flag;
- (NSArray *)constraints;                          // 回傳視圖建立的約束
- (void)addConstraint:(NSLayoutConstraint *)constraint;
- (void)addConstraints:(NSArray *)constraints;
- (void)removeConstraint:(NSLayoutConstraint *)constraint;
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize;
- (CGSize)intrinsicContentSize;                    // 回傳視圖的原生大小
- (void)invalidateIntrinsicContentSize;

此外還有壓縮阻力與延展優先級(contentCompressionResistancePriority/contentHuggingPriority)、對齊(alignmentRectForFrame: 等)、觸發更新約束(setNeedsUpdateConstraints、updateConstraintsIfNeeded)與除錯(constraintsAffectingLayoutForAxis:、hasAmbiguousLayout)等相關方法。

繪製與更新

- (void)drawRect:(CGRect)rect;                  // 在指定區域繪製視圖
- (void)setNeedsDisplay;                         // 標記整個邊界需重繪
- (void)setNeedsDisplayInRect:(CGRect)invalidRect;

座標轉換與點擊測試

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

狀態保存與恢復、標記

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder;
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder;
- (UIView *)viewWithTag:(NSInteger)tag;

最後還有視圖變動的通知方法,如 didAddSubview:、willRemoveSubview:、willMoveToSuperview:、didMoveToSuperview、willMoveToWindow:、didMoveToWindow 等。以上是 UIView 的實例方法,我依官方文件分類整理,方便日後查閱,少走冤枉路。歡迎指正——LC。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved