UIView之常用方法

时间:2023-03-09 03:58:54
UIView之常用方法

UIView之常用方法

  • 将一个视图添加为子视图,并使之在最上面显示
    -(void)addSubView:(UIView *)view;
  • 将指定子视图移动到顶部
    -(void)bringSubViewToFront:(UIView *)view;
  • 将指定之视图放到最下面
    -(void)sendSubViewToBack:(UIView *)view;
  • 将指定视图添加到subviews数组的index位置
    -(void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
  • 将指定视图添加到指定子视图下面
    -(void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
  • 将指定视图添加到指定子视图上面
    -(void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
  • 交换subviews数组中两个位置的子视图
    -(void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
  • 从父视图中移除
    -(void)removeFromSuperview;
  • 根据tag值获取对应的子孙控件
    -(UIView *)viewWithTag:(NSInteger)tag;
  • 将视图中点从自己的坐标系转换到指定的视图坐标系中
    -(CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
  • 将指定视图中坐标系内的某点转换到自己的坐标系中
    -(CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
  • 将视图中矩形区域从自己的坐标系转换到指定的视图坐标系中
    -(CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
  • 将指定视图中坐标系内的矩形区域转换到自己的坐标系中
    -(CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
  • 刷新视图,调用后自动调用drawRect:(CGRect)rect
    -(void)setNeedsDisplay;

  • 继承自UIResponder用于响应触摸事件的方法
1.- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
2.- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
3.- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
4.- (void)touchesCancelled:(nullable NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;

以上方法需要自定义view重写,若需要对触摸点到判断(使用)那么重写方法时,在方法体内首先获取触摸点:

1.UITouch *touch = [touches anyObject];
2.CGPoint point = [touch locationInView:self];

  • 动画
1.// 首先需要设置动画头,告诉编译器下面是动画
2.[UIView beginAnimations:nil context:nil];
3.// 再设置动画执行的配置、动画
4.[UIView setAnimationDuration:0.5];
5.[UIView setAnimationRepeatCount:2];
6.[UIView setAnimationDelay:3.0];
7.// balabala需要执行的动画
8. ................
9.// 最后提交动画
10.[UIView commitAnimations];
  • 使用block设置动画
    • 方法一
      +(void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations;
    • 方法二
      +(void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion
    • 方法三
      + (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion