UIButton

IOS commonly used components and layout, personal learning records, records only.

//- (IBAction)minus:(id)sender { // NSLog(@"minus"); // CGRect originFrame = self.btnIcon.frame; // originFrame.size.width -= 10; // originFrame.size.height -= 10; // // originFrame.origin.x += 5; // originFrame.origin.y += 5; // self.btnIcon.frame = originFrame; //} // //- (IBAction)add:(id)sender { // NSLog(@"add"); // CGRect originFrame = self.btnIcon.frame; // originFrame.size.width += 10; // originFrame.size.height += 10; // // originFrame.origin.x -= 5; // originFrame.origin.y -= 5; // self.btnIcon.frame = originFrame; //} // //- (IBAction)right:(id)sender { // NSLog(@"right"); // CGRect originFrame = self.btnIcon.frame; // originFrame.origin.x += 10; // self.btnIcon.frame = originFrame; //} // //- (IBAction)left:(id)sender { // NSLog(@"left"); // CGRect originFrame = self.btnIcon.frame; // originFrame.origin.x -= 10; // self.btnIcon.frame = originFrame; //} // //- (IBAction)down:(id)sender { // NSLog(@"down"); // CGRect originFrame = self.btnIcon.frame; // originFrame.origin.y += 10; // self.btnIcon.frame = originFrame; //} // //- (IBAction)up { // NSLog(@"up"); // CGRect originFrame = self.btnIcon.frame; // originFrame.origin.y -= 10; // self.btnIcon.frame = originFrame; //} - (IBAction)zoom:(UIButton *)sender { CGFloat gap = 100; CGRect bounds = self.btnIcon.bounds; Switch (sender.tag) {case 1011: // Enlarge bounds. Size. Height += gap; bounds.size.width += gap; break; Case 1012: // Reduce bounds. Size. Height -= gap; bounds.size.width -= gap; break; } // // perform animations // // 1. Start animations // [UIView beginAnimations:nil Context :nil]; // // 2. Set the animation time // [UIView setAnimationDuration:1]; // // // 3. Animation execution // self.btnicon. bounds = bounds; // // // 4. CommitAnimations // [UIView commitAnimations]; [UIView animateWithDuration:1.0 animations:^{self.btnicon. bounds = bounds;} completion:^(BOOL finished) {NSLog(@" end of animation ");}]; } - (IBAction)moveIcon:(UIButton *)sender { CGFloat gap = 100; CGPoint centerPoint = self.btnIcon.center; Switch (sender.tag) {case 1001: // left centerPoint. X -= gap; break; Case 1002: // centerPoint. Y -= gap; break; Case 1003: // right centerPoint. X += gap; break; Case 1004: // centerPoint. Y += gap; break; } // // perform animations // // 1. Start animations // [UIView beginAnimations:nil Context :nil]; // // 2. Set the animation time // [UIView setAnimationDuration:1]; // // // 3. Animation execution operation // self.btnicon.center = centerPoint; // // // 4. CommitAnimations // [UIView commitAnimations]; [UIView animateWithDuration:1.0 animations:^{self.btnicon.center = centerPoint;} completion:^(BOOL Finished) {NSLog(@" Animation over ");}]; }Copy the code

UIButton is created dynamically

#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIButton *btnIcon; @end@implementation ViewController when displaying an interface, first create the controller for that interface as soon as viewDidLoad is executed, - (void)viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. NSLog(@"viewDidLoad"); UIButton *btnIcon = [[UIButton alloc] init]; UIButton alloc = [UIButton alloc] init]; self.btnIcon = btnIcon; / / 2. Set button properties [btnIcon setTitle: @ "point me" forState: UIControlStateNormal]; [btnIcon setTitle: @ "you see what" forState: UIControlStateHighlighted]; / / set the background 2.2 [btnIcon setBackgroundImage: [UIImage imageNamed: @ "icon1"] forState: UIControlStateNormal]; [btnIcon setBackgroundImage:[UIImage imageNamed:@"icon2"] forState:UIControlStateHighlighted]; / / set the font color 2.3 [btnIcon setTitleColor: [UIColor redColor] forState: UIControlStateNormal]; [btnIcon setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted]; // 2.4 Set the size btnicon. frame = CGRectMake(100, 100, 100, 100); / / 2.5 set up to monitor [btnIcon addTarget: self action: @ the selector (iconClick) forControlEvents: UIControlEventTouchUpInside]; [self.view addSubview:btnIcon]; } -(void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; NSLog(@"didReceiveMemoryWarning"); } - (void) iconClick { NSLog(@"iconClick"); } @endCopy the code

UIView animation

/ / based on original value scale self. BtnIcon. Transform = CGAffineTransformMakeScale (1.5, 1.5); Transform = CGAffineTransformScale(self.btnicon.transform, 1.5, 1.5); / / based on original value rotation self. BtnIcon. Transform = CGAffineTransformMakeRotation (90); Transform = CGAffineTransformRotate(self.btnicon.transform, M_PI_4); // Rotate M_PI_4 = 45° self.btnicon.transform = CGAffineTransformRotate(self.btnicon.transform, M_PI_4); [UIView animateWithDuration:2.5 animations:^{self.btnicon.transform = CGAffineTransformTranslate(self.btnIcon.transform, 50, 50); self.btnIcon.transform = CGAffineTransformRotate(self.btnIcon.transform, Transform = CGAffineTransformScale(self.btnicon.transform, 1.5, 1.5);}]; // Parent control sender.superview; / / all child controls sender. Superview. Subviews. / / get or have a child controls, change the background color for (UIView * subView in sender. Superview. Subviews) {[subView setBackgroundColor: [UIColor redColor]]. } / / to remove all child controls while (self. View. Subviews. FirstObject) {[self. View. Subviews. FirstObject removeFromSuperview]; } / / translation based on original value self. BtnIcon. Transform = CGAffineTransformMakeTranslation (0, 50); / / based on the current value of translational self. BtnIcon. Transform = CGAffineTransformTranslate (self) btnIcon) transform, 0, - 50); / / restorable self. BtnIcon. Transform = CGAffineTransformIdentity;Copy the code

Image browsing

#import "ViewController.h" @interface ViewController () @property(nonatomic, strong) NSArray * pics; @property(nonatomic, assign) int index; @property (weak, nonatomic) IBOutlet UIImageView *ivLoading; @property (weak, nonatomic) IBOutlet UIImageView *ivPic; @property (weak, nonatomic) IBOutlet UILabel *labelIndex; @property (weak, nonatomic) IBOutlet UILabel *labelTitle; - (IBAction)next:(UIButton *)sender; - (IBAction)pre:(UIButton *)sender; - (void) setImage:(int) index; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. NSLog(@"pics = %@", self.pics); [self setImage:0]; // bdp_anim_loading_small_blue_001 NSMutableArray *arrayM = [NSMutableArray array]; for (int i = 0; i < 12; i++) { [arrayM addObject:[UIImage imageNamed:[NSString stringWithFormat:@"bdp_anim_loading_small_blue_%03d", i+1]]]; // NSString *imageName = [NSString stringWithFormat:@"bdp_anim_loading_small_blue_%03d.png", i+1]; // NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil]; // NSLog(@"path = %@", path); // [arrayM addObject:[UIImage imageWithContentsOfFile:path]]; } NSLog(@"arrayM = %@", arrayM); / / by [UIImage imageNamed] will always exist in memory cache for the image, does not automatically release / / solution: use [UIImage imageWithContentsOfFile: path] loading / / 1. Set the UIImageView animationImages data source self. IvLoading. AnimationImages = arrayM; / / 2. Set the duration self. IvLoading. AnimationDuration = arrayM. Count * 0.1; / / 3. Whether repeat play self. IvLoading. AnimationRepeatCount = NSIntegerMax; // 4. Start animation [self.ivLoading startAnimating]; . / / the self ivLoading animation / / want to consider the self ivLoading. AnimationImages pointer release} - pics (NSArray *) {/ / lazy loading the if (_pics = = nil) { NSString *path = [[NSBundle mainBundle] NSString *path = [NSBundle mainBundle] pathForResource:@"picInfo.plist" ofType:nil]; _pics = [NSArray arrayWithContentsOfFile:path]; } return _pics; } - (IBAction)pre:(UIButton *)sender { [self setImage: self.index - 1]; } - (IBAction)next:(UIButton *)sender { [self setImage: self.index + 1]; } - (void) setImage:(int) index { if (index < 0 || index >= self.pics.count) { return; } self.index = index; NSDictionary *data = self.pics[index]; self.ivPic.image = [UIImage imageNamed:data[@"icon"]]; self.labelTitle.text = data[@"title"]; self.labelIndex.text = [NSString stringWithFormat:@"%d / %lu", self.index + 1, self.pics.count]; } @endCopy the code

picInfo.plist

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE plist PUBLIC "- / / / / DTD plist Apple / 1.0 / EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd" > < plist Version ="1.0"> <array> <key>icon</key> <string> PIC1 </string> <key>title</key> <string> <dict> <key>icon</key> <string>pic2</string> <key> </key> <key>title</key> <string> Lost sets </string> </dict> <dict> <key>icon</key> <string>pic3</string> <key>title</key> <string> Jade set </string> </dict> </array> </plist>Copy the code

Xib and UIView

  1. Create a xib

  1. Create a custom View that inherits from UIView.

  1. Xib associates a custom View

Note that xib is associated with UIView:

  1. Set class in File’s Owner to delete
  2. If File’s Owner has a set association to remove the close attribute, the association can only be set in the View. This is a bit different from when the ViewController created the Xib. The properties associated with the ViewController are all associated with the File’s Owner

Associate the control drag line on the XIB with the custom View.

// AppView.h #import <UIKit/UIKit.h> #import "ModelAppView.h" @interface AppView : UIView @property(nonatomic, strong) ModelAppView *model; @end // AppView.m #import "AppView.h" @interface AppView () @property (weak, nonatomic) IBOutlet UIImageView *ivIcon; @property (weak, nonatomic) IBOutlet UILabel *tvDect; @property (weak, nonatomic) IBOutlet UIButton *btnDownload; @end @implementation AppView - (void)setModel:(ModelAppView *)model { _model = model; self.ivIcon.image = [UIImage imageNamed:@"ic_launcher"]; self.tvDect.text = model.name; } + (instancetype) appView { NSBundle *rootBundle = [NSBundle mainBundle]; return [[rootBundle loadNibNamed:@"AppView" owner:nil options:nil] firstObject]; } @end // create a custom view in ViewController AppView *view = [AppView AppView]; // Set the coordinates CGFloat viewX = (gap + subViewWidth) * c + gap; CGFloat viewY = (gap + subViewHeight) * r + gap; view.frame = CGRectMake(viewX, viewY, subViewWidth, subViewHeight); // Set view Model [self.view addSubview:view]; // Add view view.model = self.appinfos [I];Copy the code

Display it

- (UILabel *) showMsg:(NSString *) msg { UILabel *msgView = [[UILabel alloc] init]; msgView.text = msg; CGFloat sw = self.superview.frame.size.width; CGFloat sh = self.superview.frame.size.height; CGFloat msgW = sw * 0.7; CGFloat msgH = 30; CGFloat msgX = (sw - msgW) / 2; CGFloat msgY = (sh - msgH) / 2; msgView.frame = CGRectMake(msgX, msgY, msgW, msgH); [msgView setTextColor:[UIColor whiteColor]]; [msgView setBackgroundColor:[UIColor blackColor]]; [msgView setTextAlignment:NSTextAlignmentCenter]; MsgView. Alpha = 0.0; msgView.layer.cornerRadius = 10; msgView.layer.masksToBounds = YES; [UIView animateWithDuration:1.0 animations:^{msgviet. alpha = 0.6;} completion:^(BOOL finished) {if (finished) { [UIView animateWithDuration:0.5 delay:1.0 options:nil animations:^{msgViet. alpha = 0;} completion:^(BOOL finished) { [msgView removeFromSuperview]; }]; } }]; [self.superview addSubview:msgView]; return msgView; }Copy the code

Code snippet – quick editing

UIScrollView

Set to the specified position, scroll animation

Hide scroll indicator

/ / set the content of the UIScrollView padding of the self. The scrollView. ContentInset = UIEdgeInsetMake,10,10,10 (10);Copy the code

UIScrollView uses a proxy to listen for scrolling
@interface ViewController () <UIScrollViewDelegate> @property(nonatomic, weak) IBOutlet UIScrllView *scrollView; @property(nonatomic, weak) IBOutlet UIImageView *imageView; @end @implementation ViewController - (void) viewDidLoad { [super viewDidLoad]; self.scrollView.contentSize = self.imageView.image.size; self.scrollView.delegate = self; / / set the UIScrollView zoom ratio, configuration and viewForZoomInScrollView correction using the self. The scrollView. MaximunZoomScale = 3.5; The self. The scrollView. MinimunZoomScale = 0.5; } / / UIScrollViewDelegate protocol method - (void) scrollViewWillBeginDragging: (UIScrollView *) scrollView {NSLog (@ "is about to begin drag"); } - (void) scrollViewDidScroll:(UIScrollView *) scrollView {NSLog(@" rolling "); } - (void) scrollViewDidEndDragging: (UIScrollView *) scrollView {NSLog (@ "drag and drop over"); } // UIScrollView - (void) viewForZoomInScrollView (UIScrollView *) scrollView {return self.imageView; } - (void) scrollViewWillBeginZooming: (UIScrollView *) scrollView {NSLog (@ "to scale"); } - (void) scrollViewDidZoom:(UIScrollView *) scrollView {NSLog(@" scaling "); } - (void) scrollViewDidEndZooming (UIScrollView *) scrollView {NSLog(@" zooming ends "); } @endCopy the code
Picture rotation chart
@interface ViewController() <UIScrollViewDelegate> @property(weak, nonatomic) IBOutlet UIScrollView *scrollView; @property(weak, nonatomic) IBOutlet UIPageControl *pageControl; @property(strong, nonatomic) NSTimer *timer; @end @implementation ViewController -(void) viewDidLoad { [super viewDidLoad]; [self loadIamgeViews]; } -(void) initIamgeViewsInScrollView { CGFloat y = 0; CGFloat w = scrollView.frame.size.width; CGFloat h = scrollView.frame.size.height; // Add a horizontal image to scrollView for(int I = 0; i < 5; i++) { UIImageView *imageView = [[UIImageView alloc] init]; Imageview. image = [UIImage imageNamed:[NSString stringWithFormat:@"img_% 02D ", I]]; CGFloat x = i * w; imageView.frame = CGRectMake(x, y, w, h); // Add to scrollView [self.scrollView addSubview:imageView]; } / / set the scrollView content size CGFloat maxW = CGRectGetMaxX (self. ScrollView. SubViews. LastObject. Frame). self.scrollView.contentSize = CGSizeMake(maxW, 0); / / open the paging function, a page with a scrollView width bit divided self. The scrollView. PagingEnabled = YES; / / hide the horizontal scroll bar self. The scrollView. ShowHorizontalScrollIndicator = NO: / / set the indicator pages self. PageControl. NumberOfPages = ceil (maxW/self. ScrollView. Frame. Szie. Width); / / set the current page, in UIScrollViewDetegate scrollViewDidScroll dynamic calculation of the current page number self. PageControl. CurrentPage = 0; // Start timer NSTimer(large interval, 1 2 seconds), CADisplayLink(small interval, 0.0x seconds) [self startTime]; StartTime {} - (void) self. Time = [NSTimer scheduledTimeWithInterval: 1.0 target: self selector: @ the selector (scrollImage) userInfo:nil repeats:YES]; // Create a message loop object NSRunLoop * runLoop = [NSRunLoop currentRunLoop]; / / change the self. The timer object's priority [runLoop addTimer: self. The timer forMode: NSRunLoopCommonModes]; / / set the pageControl in scrollView is the top View / / [self. The scrollView bringSubviewToFront: self. The pageControl]; } - (void) nextPageOfScrollView { NSInteger page = self.pageControl.currentPage; If (page = = self. PageControl. NumberOfPages - 1) {/ / jump to the first page page = 0; } else {// next page page++; } / / jump CGFloat offsetX = page * self scrollView. Frame. The size. The width; [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES]; } / / drag the - (void) scrollViewWillBeginDragging: (scrollView UIScrollView *) {/ / stop the timer, [self.timer invalidate]; [self.timer invalidate]; self.timer = nil; } // is scrolling - (void) scrollViewDidScroll:(UIScrollView *) scrollView {// dynamically calculate pageControl current page number // 1. Get the current offset CGFloat offsetX = scrollView. CurrentOffset. X. / / 1.1 use offset plus half a page width, drag and drop to half hour already can confirm switch pages offsetX + = scrollView. Frame. The size. The width; / / 2. Deviation divided by the scrollView width, gets the current page int page = offsetX/scrollView. Frame. The size. The width; / / 3. Set the indicator pages self. PageControl. CurrentPage = page; } / / drag the end - (void) scrollViewDidEndDragging: (UIScrollView *) scrollView {[self startTime); } @endCopy the code

UICollectionView Stream list

# import "ViewController. H" / / UICollectionViewDelegateFlowLayout UICollectionViewDelegate agreement @ interface inheritance ViewController () <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; / / create a layout layout UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init]; / / set the layout direction to vertical flow layout / / layout scrollDirection = UICollectionViewScrollDirectionVertical; layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // Set the size of each item to 100*100 layout.itemSize = CGSizeMake(150, 40); / / create collectionView pass strategy layout to create a layout UICollectionView * collect = [[UICollectionView alloc] initWithFrame: self. The frame  collectionViewLayout:layout]; Collect. delegate=self; collect.dataSource=self; / / registered item type Here use the type of the system/collect registerClass: [UICollectionViewCell class] forCellWithReuseIdentifier: @ "cellid"]. [self.view addSubview:collect]; } # pragma UICollectionViewDataSource -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 300;  } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath  *)indexPath { UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath]; // indexPath.item; Cell.backgroundcolor = [UIColor colorWithRed: arc4Random ()%255/255.0 Green: arc4Random ()%255/255.0 Alpha blue: arc4random () % 255/255.0:1); return cell; } # pragma UICollectionViewDelegateFlowLayout -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return CGSizeMake(40, arc4random()%50 + 50); } @endCopy the code

Screen adaptation

1. autoresizing

Autolayout needs to be shut down

// Use autoresizing @interface ViewControler () @implementation ViewControler - (void) viewDidLoad {// Parent View UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; BlueView. Frame = CGRectMake,0,200,200 (0); [self.view addSubview:blueView]; // subviewQ UIView *redView = [[UIView alloc] init]; redView.backgroundColor = [UIColor redColor]; int redW = blueView.frame.size.width; int redH = 50; int redX = 0; int redY = blueView.frame.size.height - redH; redView.frame = CGRectMake(redX,redY,redW,redH); [blueView addSubview:redView]; / / set autoresizing anchor right redView. AutoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth; / / UIViewAutoresizingFlexibleLeftMargin variable on the left, on the right side of the fixed / / UIViewAutoresizingFlexibleTopMargin coping variable, At the bottom of the fixed / / UIViewAutoresizingFlexibleWidth width changes over the parent} @ the endCopy the code

2. autolayout

  • With reference to
  • The constraint

Constraint where to add

  1. The constraint doesn’t matter to other views; the constraint is added to itself
  2. The constraint refers to the parent class on which the constraint is added
  3. The constraint is added to the common parent class by referring to the sibling view

Code creation constraints

@interface ViewControler () @end @implementation ViewContraler - (void) viewDidLoad { [super viewDidLoad]; UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; / / blueView. Frame = CGRectMake,0,100,100 (0); [self.view addSubview:blueView]; UIView *redView = [[UIView alloc] init]; redView.backgroundColor = [UIColor redColor]; / / redView frame = CGRectMake (100100100100); [self.view addSubview:redView]; / / 3. Prohibit autoresizing blueView. TranslatesAutoresizingMaskIntoConstraints = NO. redView.translatesAutoresizingMaskIntoConstraints = NO; 4.1.1 blueView height constraint is 50: Multipler plus constant NSLayoutConstraint *blueViewH = [NSLayoutConstrain ConstraintWithItem: blueView attribute: NSLayoutAttributeHeight / / blueView highly relatedBy: NSLayoutRelationEqual / / equal to zero ToItem: nil attribute: NSLayoutAttributeNOtAnAttribute / / without refer to objects and attributes multiplier: / / 1.0 times the multiplier constant: / / plus 50 constant ]; [blueView addConstraint:blueViewH]; // Add constraint to blueView // 4.1.2 blueView from parent 30 NSLayoutConstraint *blueViewLeft = [NSLayoutConstrain ConstraintWithItem: blueView attribute: NSLayoutAttributeLeft / / the left blueView relatedBy: NSLayoutRelationEqual / / equal to zero ToItem: blueView superview attribute: NSLayoutAttributeLeft / / parent left multiplier: / / 1.0 times the multiplier constant: / / plus 30 constant ]; [blueView.superview addConstraint:blueViewH]; // Add constraint to blueView parent; // 4.1.2 blueView from parent 30 NSLayoutConstraint *blueViewTop = [NSLayoutConstrain ConstraintWithItem: blueView attribute: NSLayoutAttributeTop / / blueView relatedBy: above NSLayoutRelationEqual / / equal to zero ToItem: blueView superview attribute: NSLayoutAttributeTop / / parent multiplier above: / / 1.0 times the multiplier constant: / / plus 30 constant ]; [blueView.superview addConstraint:blueViewTop]; // Add constraint to blueView parent; // 4.1.2 blueView from parent 30 NSLayoutConstraint *blueViewLeft = [NSLayoutConstrain ConstraintWithItem: blueView attribute: NSLayoutAttributeRight / / blueView right relatedBy: NSLayoutRelationEqual / / equal to zero ToItem: blueView superview attribute: NSLayoutAttributeRight / / parent right multiplier: / / 1.0 times the multiplier constant: - / / plus 30 constant ]; [blueView.superview addConstraint:blueViewLeft]; 4.2.1 redView height constraint is 50: A how object is one attribute B object magic properties Multiplied by the multipler coupled with constant NSLayoutConstraint * redViewH = [NSLayoutConstrain constraintWithItem: redView Attribute: NSLayoutAttributeHeight / / redView highly relatedBy: NSLayoutRelationEqual / / equal toItem: blueView Attribute: NSLayoutAttributeHeight / / blueView highly multiplier: / / 1.0 times the multiplier constant: 0 / / plus the constant]; [redView.superview addConstraint:redViewH]; // Add constraint to redView parent // 4.1.2 redView from blueView bottom 30 NSLayoutConstraint *redViewTop = [NSLayoutConstrain ConstraintWithItem: blueView attribute: NSLayoutAttributeTop / / redView relatedBy: above NSLayoutRelationEqual / / equal to zero ToItem: blueView superview attribute: NSLayoutAttributeBottom / / at the bottom of the blueView multiplier: / / 1.0 times the multiplier constant: 30 // add constant]; [blueView.superview addConstraint:redViewTop]; // Add constraint to redView parent // 4.2.3 redView vs. blueView Align NSLayoutConstraint *redViewRight = [NSLayoutConstrain ConstraintWithItem: redView attribute: NSLayoutAttributeRight / / redView right relatedBy: NSLayoutRelationEqual / / equal to zero ToItem: blueView attribute: NSLayoutAttributeRight / / blueView right multiplier: / / 1.0 times the multiplier constant: 0 / / plus constant ]; [redView.superview addConstraint:redViewRight]; NSLayoutConstraint *redViewW = [NSLayoutConstrain; // Add constraint to redView parent ConstraintWithItem: redView attribute: NSLayoutAttributeWidth relatedBy: / / redView width NSLayoutRelationEqual / / equal to zero ToItem: blueView attribute: NSLayoutAttributeRight/width/blueView multiplier: / / 0.5 times the multiplier constant: 0 / / plus constant ]; [redView.superview addConstraint:redViewW]; // Add constraints to the redView parent class // self.toplayoutGuide // status bar} @endCopy the code

Animation is implemented through Autolayout

@interface ViewController () @property(weak, nonatomic) IBOutlet UIButton *button; @property(weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint; @end @implementation ViewController -(void) move { buttonTopConstraint.constant += 100; [UIView animateWithDuration:1.5 animations:^{[self.button layoutIfNeeded];}]; } @endCopy the code