承接上篇,本篇探索 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; // 標記下一週期重新佈局
- (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。