iOS开发进阶学习

Summary

Websites

DaFont免费字体网站
NSDataFormatter用于NSDataFormatter的字符串格式
GPS-Coordinate查看地理位置的经纬度
PaintCodeApp 这个网页可以查看各iphone的尺寸
GIPHYgif图网站
SampleVideo提供测试视频下载

Info.plist

  1. Fonts provided by application/item(test.ttf) : 在程序内添加第三方字体
  2. App Transport Security Settings/Allow Arbitrary Loads(YES):允许进行http请求
  3. Privacy - Location Always Usage Description: 前台和后台获取用户定位请求时获得许可 博客链接
  4. Privacy - Photo Library Additions Usage Description | Privacy - Photo Library Usage Description:允许用户访问照片
  5. Privacy - Camera Usage Description:允许使用相机

推荐配置

  1. 字体:Avenir (Light) 用于按钮等
  2. 字体:Avenir Next (Heavy) 用于标示比如得分
  3. 字体:Digital-7 用于显示日期时间

报错解释

  1. Expression is not assignable 博客链接
  2. [UIScreen mainScreen].bounds.size得到尺寸和应得尺寸不匹配问题
  3. 按钮不响应点击事件

2019-04-04

Theory

响应链参考链接
能相应事件的必须是UIResponder的子类(UIView,UIViewController,UIApplication)
当手指触碰屏幕时,会将此事件包装成UIEvent,由UIApplication放到队列中,并取出队列中第一个事件,沿着UIWindow->UIView->父视图->子视图的顺序传递,每传递到一个控件就会调用:

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
返回视图层级中能响应触控点的最深视图
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
返回视图是否包含指定的某个点

直到找到最合适的视图

UI

Aspect Ratio
添加constraints时,添加Aspect Ratio时可以保证高宽比不变

UIWindow & UIView
在iOS中只有一个UIWindow(UIView子类),iOS程序启动完毕后,创建的第一个视图控件就是UIWindow,接着创建控制器的View,最后将控制器的View添加到UIWindow上,于是控制器的View就显示在屏幕上了。

iOS程序启动过程参考链接

  1. 根据传递的类名创建UIApplication对象,这是第一个对象
  2. 创建UIApplication代理对象,并给UIApplicaiton对象设置代理
  3. 开启主运行循环 main events loop处理事件,保持程序一直运行
  4. 加载info.plist,判断是否指定main(xib 或者 storyboard)如果指定就去加载
    在步骤4中,会执行步骤:1)创建窗口UIWindow 2)加载mian.storyboard 并实例化view controller 3)分配新视图控制器到窗口root viewcontroller,然后使窗口显在示屏幕上

UIView.alpha = 0 VS UIView.hidden = YES
二者都可以将view及其子视图隐藏掉,且从相应链中去掉,但是hidden还可以相应autolayout和resizing,而alpha会显示动画效果,如果之后还会再用,建议使用hidden

Xcode

Storyboard UIHierarchy
查看storyboard的UI Hierarchy ,首先要运行,然后在Navigator的Debug Navigator中的“门型”按钮选择View UI Hierarchy

Main Interface
General / Deployment Info下可以设置Main Interface,就是视图加载的入口

status bar
General / Deployment Info下可以设置status bar 为 default(黑)/light(白),但是需要在info.plist里添加 View controller-based status bar appearance,并将值设置为NO

Class & Object

UIGestureRecognizer参考链接
这是一个抽象类,不允许对其实例化

注意事项:

  1. 父视图添加了action,子视图没添加,则点击子视图也会触发
  2. 父视图和子视图都添加了action,点击子视图只会触发子视图action
  3. 视图连续添加多个UIGestureRecognizer,只会触发最后一个添加的

Code Block

AudioToolBox播放音乐

//.h
#import <AudioToolbox/AudioToolbox.h>

//.m
@interface ViewController () {
    SystemSoundID soundId;
}
@property (weak, nonatomic) IBOutlet UILabel *MeowLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.MeowLabel.hidden = YES;
    NSURL* url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Cat" ofType:@".wav" ]];
	//或直接:
	NSURL* url = [[NSBundle mainBundle] URLForResource:@"Sound" withExtension:@"wav"];
                  
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundId);
}

- (IBAction)cat:(id)sender {
    AudioServicesPlaySystemSound(soundId);
    
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(hideLabel) userInfo:nil repeats:NO];
}

- (void) hideLabel{
    self.MeowLabel.hidden = NO;
}

@end

2019-04-06

Code Block

UITextView禁止换行
先加协议<UITextViewDelegate>,将代理设置为UIViewController

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound) {
        return YES;
    }
    
    [textView resignFirstResponder];
    return  NO;
}

给UIView添加触碰事件

UITapGestureRecognizer* redTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(redTapAction)];

[self.RedView addGestureRecognizer:redTapGestureRecognizer];

改变文本属性
包括文本字体、颜色,shadow

- (IBAction)setColor:(id)sender {
    self.label.textColor = [UIColor redColor];
}
- (IBAction)setBackgoundColor:(id)sender {
    self.label.backgroundColor = [UIColor greenColor];
}
- (IBAction)setFontSize:(id)sender {
    [self.label setFont:[UIFont fontWithName:@"Futura" size:25]];
}
- (IBAction)setDropShadow:(id)sender {
    self.label.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.label.layer.shadowOpacity = 0.5;
    self.label.layer.shadowRadius = 2.0f;
    self.label.layer.shadowOffset = CGSizeMake(2, 2);
}
- (IBAction)setShadowColor:(id)sender {
    self.label.layer.shadowColor = [[UIColor blueColor] CGColor];
}
- (IBAction)setLeft:(id)sender {
    self.label.textAlignment = NSTextAlignmentLeft;
}
- (IBAction)setRight:(id)sender {
    self.label.textAlignment = NSTextAlignmentRight;
}
- (IBAction)setCenter:(id)sender {
    self.label.textAlignment = NSTextAlignmentCenter;
}

动画

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:5];
    
self.label.alpha = 0;
    
[UIView commitAnimations];

NSTimer 计时器

- (IBAction)start:(id)sender {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}

- (IBAction)pause:(id)sender {
    [self.timer invalidate];
}
- (IBAction)restart:(id)sender {
    [self.timer invalidate];
    self.label.text = @"0";
}

- (void) updateTime{
    counter++;
    self.label.text = [NSString stringWithFormat:@"%d",counter];
}

NSDate日期时间

@property (nonatomic, strong) NSDateFormatter* dateFormatter;
self.dateFormatter = [[NSDateFormatter alloc]init];
    
//self.dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
self.dateFormatter.dateFormat = @"HH:mm:ss";
// [self.dateFormatter setDateFormat:@"HH:mm:ss"];

- (void) updateTime{
    self.label.text = [self.dateFormatter stringFromDate:[NSDate date]];
}

2019-04-07

Theory

frame & bounds参考链接
frame和bounds都是CGRect,但frame表示在父View下的坐标,bounds表示自己的坐标

viewWillLayoutSubviews
在以下情况会调用

  1. init初始化不会触发layoutSubviews
  2. addSubview会触发layoutSubviews
  3. 设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化
  4. 滚动一个UIScrollView会触发layoutSubviews
  5. 旋转Screen会触发父UIView上的layoutSubviews事件
  6. 改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件

Code Block

生成随机数

arc4random()%100 // 0-99

int max = 100
int min = 50
arc4random_uniform(max - min) + min // 50-99

performer主动触发事件

[self performSelector:@selector(performer) withObject:nil afterDelay:3];

- (void) performer{
    NSLog(@"End...");
}

读取.plist

NSString* path = [[NSBundle mainBundle] pathForResource:@"images" ofType:@"plist"];
    
NSDictionary* dict = [[NSDictionary alloc]initWithContentsOfFile:path];
NSLog(@"%@",dict);
NSMutableArray* array = dict[@"images"];

操作UISwitch

- (IBAction)switchChange:(UISwitch *)sender {
    if (sender.on) {
        NSLog(@"On");
    } else{
        NSLog(@"Off");
    }
}

操作UISegmentedControl


- (IBAction)segmentChange:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
            NSLog(@"0");
            break;
        case 1:
            NSLog(@"1");
            break;
        case 2:
            NSLog(@"2");
            break;
        default:
            break;
    }
}

操作UISlider

- (IBAction)sliderChange:(UISlider *)sender {
    NSLog(@"%f",sender.value);
}

操作UIAlertController/ActionSheet

- (IBAction)showAlert:(UIButton *)sender {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Message" message:@"Nothing important" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* action1 = [UIAlertAction actionWithTitle:@"Button 1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Button 1");
    }];
    
    UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"Button 2" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Button 2");
    }];
    
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Button 1" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

UIAlertController/Alert

- (IBAction) showAlert:(id)sender{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Message" message:@"Nothing important" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* action = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:nil];
    
    UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:nil];
    
    
    
    [alert addAction:action];
    [alert addAction:action2];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}

跳转到safiri并打开网页

- (IBAction)showURL:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.baidu.com"] options:nil completionHandler:nil];
}

检测抖动

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (event.subtype == UIEventSubtypeMotionShake) {
        self.shakingLabel.text = @"Waoooo";
    }
}

添加滑动事件

    self.upSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    self.downSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    self.leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    self.rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    
    self.upSwipe.direction = UISwipeGestureRecognizerDirectionUp;
    self.downSwipe.direction = UISwipeGestureRecognizerDirectionDown;
    self.leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    self.rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.view addGestureRecognizer:self.upSwipe];
    [self.view addGestureRecognizer:self.downSwipe];
    [self.view addGestureRecognizer:self.leftSwipe];
    [self.view addGestureRecognizer:self.rightSwipe];
    
    
}

- (void) handleSwipe:(UISwipeGestureRecognizer*) swipe{
    if (swipe.direction == UISwipeGestureRecognizerDirectionUp) {
        self.shakingLabel.text = @"up swipe";
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionDown){
        self.shakingLabel.text = @"down swipe";
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionLeft){
        self.shakingLabel.text = @"left swipe";
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionRight){
        self.shakingLabel.text = @"right swipe";
    }
}

通过使用UIPanGestureRecognizer并改变bounds实现UIScrollView效果
参考链接

    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    [self.view addGestureRecognizer:pan];
}

- (void) panAction:(UIPanGestureRecognizer*) pan{
    CGPoint touchPoint = [pan translationInView:self.view];
    
    //NSLog(@"x=%f,y=%f",touchPoint.x,touchPoint.y);
    
    CGRect newBounds = self.view.bounds;
    newBounds.origin.x -= touchPoint.x;
    newBounds.origin.y -= touchPoint.y;
    self.view.bounds = newBounds;
    [pan setTranslation:CGPointZero inView:self.view];
    

}

实现UIScrollView的ContentSize

    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    [self.view addGestureRecognizer:pan];
}

- (void) panAction:(UIPanGestureRecognizer*) pan{
    //ContentSize
    CGPoint touchPoint = [pan translationInView:self.view];
    CGFloat newOriginY = self.view.bounds.origin.y - touchPoint.y;
    CGFloat newOriginX = self.view.bounds.origin.x - touchPoint.x;
    
    CGFloat minOriginY = 0.0;
    CGFloat minOriginX = 0.0;
    CGFloat maxOriginY = 20.0;
    CGFloat maxOriginX = 20.0;
    
    CGRect viewBounds = self.view.bounds;
    viewBounds.origin.y = fmax(minOriginY, fmin(newOriginY, maxOriginY));//比最大值小的同时比最小值大:min<=newOriginY<=maxOriginY
    viewBounds.origin.x = fmax(minOriginX, fmin(newOriginX, maxOriginX));
    self.view.bounds = viewBounds;
    [pan setTranslation:CGPointZero inView:self.view];
    

}

实现UIScrollView的ContentInSet

- (void)handlePanGesture:(UIPanGestureRecognizer *)panGestureRecognizer {

    //ContentInset
    CGPoint touchPoint = [panGestureRecognizer translationInView:self.view];//获取手势位置
    CGFloat newOriginY = self.view.bounds.origin.y - touchPoint.y;//根据手势位置计算新的origin值
    CGFloat newOriginX = self.view.bounds.origin.x - touchPoint.x;

    CGFloat min = 0.0;
    CGFloat maxOriginY = 600.0;
    CGFloat maxOriginX = 0;

    if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        min = 0.0;
        maxOriginY = 600.0;
    } else {
        min = -50.0;
        maxOriginY = 650.0;
    }

    CGRect viewBounds = self.view.bounds;
    viewBounds.origin.y = fmax(min, fmin(newOriginY, maxOriginY));//比最大值小的同时比最小值大:min<=newOriginY<=maxOriginY
    viewBounds.origin.x = fmax(0, fmin(newOriginX, maxOriginX));
    self.view.bounds = viewBounds;
    [panGestureRecognizer setTranslation:CGPointZero inView:self.view];

}

ScrollView实现背景图移动参考链接
参考链接2

- (UIImageView *)imageView{
    if (_imageView == nil) {
        _imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image"]];
    }
    return _imageView;
}

- (UIScrollView *)scrollView{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        _scrollView.backgroundColor = [UIColor blackColor];
        _scrollView.contentSize = self.imageView.frame.size;
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    
}

2019-04-08

UI

ViewController生命周期
参考链接
参考链接2

Code Block

UIPickerView

@interface ViewController () <UIPickerViewDataSource,UIPickerViewDelegate>

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.array.count;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    self.label.text = self.array[row];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.array[row];
}

UIDatePickerVIew


- (IBAction)datePicker:(UIDatePicker *)sender {
    self.label.text = [self.dateFormatter stringFromDate:sender.date];
}

2019-04-09

Code Block

WKWebView

导入WKWebView必须在Linked Frameworks and Libraries中添加WKWebView

@interface ViewController () <WKUIDelegate,WKNavigationDelegate>

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.jd.com"]]];
}
- (IBAction)stop:(id)sender {
}
- (IBAction)refresh:(id)sender {
    [self.webView reload];
}
- (IBAction)rewind:(id)sender {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }
}
- (IBAction)forward:(id)sender {
    if (self.webView.canGoForward) {
        [self.webView goForward];
    }
}

WKWebView + ActivityIndicator

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.jd.com"]]];
    
    [self.webView addSubview:self.actInt];
    //[self.actInt startAnimating];
}
- (IBAction)stop:(id)sender {
}
- (IBAction)refresh:(id)sender {
    [self.webView reload];
}
- (IBAction)rewind:(id)sender {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }
}
- (IBAction)forward:(id)sender {
    if (self.webView.canGoForward) {
        [self.webView goForward];
    }
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    [self.actInt startAnimating];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.actInt stopAnimating];
}

WKWebView + ActInt + SearchBar

@interface ViewController () <WKUIDelegate,WKNavigationDelegate,UISearchBarDelegate>

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"search bar clicked");
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@",searchBar.text]]]];
    [searchBar resignFirstResponder];
    
}

MKMapView + MKAnnotation

// MapPin.h
@interface MapPin : NSObject <MKAnnotation>

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end

// ViewController.m
#import <MapKit/MapKit.h>
#import "MapPin.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@property (nonatomic, strong) MapPin* pin;
@property (nonatomic, assign) MKCoordinateRegion coordRegion;

@end

@implementation ViewController

- (MapPin *)pin{
    if (_pin == nil) {
        _pin = [[MapPin alloc]init];
    }
    return _pin;
}

- (void) initCoordRegion{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    
    CLLocationCoordinate2D location;
    location.latitude = 23.060056663194118;
    location.longitude = 113.39150207918885;
    
    MKCoordinateRegion tempRegion;
    tempRegion.center = location;
    tempRegion.span = span;
    
    self.coordRegion = tempRegion;
    self.pin.coordinate = location;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCoordRegion];
    [self.mapView setRegion:self.coordRegion animated:YES];
    [self.mapView addAnnotation:self.pin];
    
    
}
- (IBAction)change2Standard:(id)sender {
    self.mapView.mapType = MKMapTypeStandard;
}
- (IBAction)change2Satelite:(id)sender {
    self.mapView.mapType = MKMapTypeSatellite;
}
- (IBAction)change2Hybrid:(id)sender {
    self.mapView.mapType = MKMapTypeHybrid;
}
- (IBAction)change2Locate:(id)sender {
    //self.mapView.mapType = MKMapType
}
- (IBAction)getDirections:(id)sender {
}


@end

MKMapView + CLLocationManager获取用户定位

#import <MapKit/MapKit.h>
#import "MapPin.h"
@interface ViewController () <CLLocationManagerDelegate,MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@property (nonatomic, strong) MapPin* pin;
@property (nonatomic, assign) MKCoordinateRegion coordRegion;
@property (nonatomic, strong) CLLocationManager* manager;

@end

@implementation ViewController

- (CLLocationManager *)manager{
    if (_manager == nil) {
        _manager = [[CLLocationManager alloc]init];
    }
    return _manager;
}

- (MapPin *)pin{
    if (_pin == nil) {
        _pin = [[MapPin alloc]init];
    }
    return _pin;
}

- (void) initCoordRegion{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    
    CLLocationCoordinate2D location;
    location.latitude = 23.060056663194118;
    location.longitude = 113.39150207918885;
    
    MKCoordinateRegion tempRegion;
    tempRegion.center = location;
    tempRegion.span = span;
    
    self.coordRegion = tempRegion;
    self.pin.coordinate = location;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager.delegate = self;
    self.mapView.delegate = self;
    //[self initCoordRegion];
    //[self.mapView setRegion:self.coordRegion animated:YES];
    //[self.mapView addAnnotation:self.pin];
    
    
}
- (IBAction)change2Standard:(id)sender {
    self.mapView.mapType = MKMapTypeStandard;
}
- (IBAction)change2Satelite:(id)sender {
    self.mapView.mapType = MKMapTypeSatellite;
}
- (IBAction)change2Hybrid:(id)sender {
    self.mapView.mapType = MKMapTypeHybrid;
}
- (IBAction)change2Locate:(id)sender {
    [self.manager requestAlwaysAuthorization];
    [self.manager requestWhenInUseAuthorization];
    
    [self.manager startUpdatingLocation];
    self.mapView.showsUserLocation = YES;
    
}
- (IBAction)getDirections:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://maps.apple.com/maps?daddr=23.060056663194118,113.39150207918885"] options:nil completionHandler:nil];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;

    CLLocationCoordinate2D location;
    location.latitude = userLocation.coordinate.latitude;
    location.longitude = userLocation.coordinate.longitude;

    MKCoordinateRegion tempRegion;
    tempRegion.center = location;
    tempRegion.span = span;

    self.coordRegion = tempRegion;
    self.pin.coordinate = location;

    [self.mapView setRegion:self.coordRegion];
    [self.mapView addAnnotation:self.pin];
}


@end

2019-04-10

Code Block

用url显示图片

self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://b-ssl.duitang.com/uploads/item/201903/21/20190321115753_CYRNG.jpeg"]]];

用WKWebView显示pdf

[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"answer" ofType:@"pdf"]]]];
    

UIImgeView显示动态图片

for (NSUInteger i = 1; i < 9; i++) {
        [self.imageArr addObject:[UIImage imageNamed: [NSString stringWithFormat:@"Image%lu",(unsigned long)i]]];
    }
    
    NSLog(@"imageArr length:%d",self.imageArr.count);
    
    self.imageView.animationImages = self.imageArr;
    
    [self.imageView setAnimationRepeatCount:10];
    [self.imageView setAnimationDuration:0.5];
    [self.imageView startAnimating];
    

保存图片到相册

UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, nil);

根据实际屏幕大小调节UICollectionView的cell的大小

- (CGSize) collectionView:(UICollectionView*)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    float screenWidth = [UIScreen mainScreen].bounds.size.width;
    NSLog(@"screen width:%f",screenWidth);
    float cellHeight = 190;
    float cellWidth = 190;
    
    if (screenWidth < 414.) {
        NSLog(@"resize cell size");
        cellWidth = 140;
        cellHeight = 140;
    }
    
    return CGSizeMake(cellWidth, cellHeight);
}

去除BackBarButtonItem的文字

调用相机拍照并显示

#import "ViewController.h"

@interface ViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, weak) IBOutlet UIImageView* imageView;

@property (nonatomic, strong) UIImagePickerController* picker;
@property (nonatomic, strong) UIImage* image;

@end

@implementation ViewController

- (UIImagePickerController *)picker{
    if (_picker == nil) {
        _picker = [[UIImagePickerController alloc]init];
    }
    return _picker;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker.delegate = self;
    
}

- (IBAction) takePhoto:(id)sender{
    [self.picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self presentViewController:self.picker animated:YES completion:nil];
    
}

- (IBAction) choosePhoto:(id)sender{
    
}

- (IBAction) savePhoto:(id)sender{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    self.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    self.imageView.image = self.image;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES  completion:nil];
}


@end

2019-04-11

Theory

  1. translatesAutoresizingMaskIntoConstraints
  2. NSDictionaryOfVariableBindings

Code Block

播放本地视频

#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

    NSURL* url = [[NSBundle mainBundle] URLForResource:@"Sound" withExtension:@"wav"];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    
    self.avController.player = self.player;
    
  
- (IBAction) playVideo{
    [self.player play];
    [self presentViewController:self.avController animated:YES completion:nil];
}

手写代码撸autolayout参考链接

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIView* view1 = [[UIView alloc]init];
    UIView* view2 = [[UIView alloc]init];
    //UIView* view3 = [[UIView alloc]init];
    
    view1.backgroundColor = [UIColor redColor];
    view2.backgroundColor = [UIColor greenColor];
    //view3.backgroundColor = [UIColor blueColor];
    
    [self.view addSubview:view1];
    [self.view addSubview:view2];
    //[self.view addSubview:view3];
    
    view1.translatesAutoresizingMaskIntoConstraints = NO;
    view2.translatesAutoresizingMaskIntoConstraints = NO;
    //view3.translatesAutoresizingMaskIntoConstraints = NO;
    
    // autolayout
    
    NSLayoutConstraint* view1TopToViewTop = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:30];
    
    NSLayoutConstraint* view1LeftToViewLeft = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:30];
    
    NSLayoutConstraint* view1RightToView2Left = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeLeft multiplier:1 constant:-30];
  
    NSLayoutConstraint* view1BottomToViewBottom = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-30];
    
    // green view
    
    NSLayoutConstraint* view2TopToViewTop = [NSLayoutConstraint constraintWithItem:view2 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:30];
    
//    NSLayoutConstraint* view2LeftToView1Right = [NSLayoutConstraint constraintWithItem:view2 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:view1 attribute:NSLayoutAttributeRight multiplier:1 constant:30];
    
    NSLayoutConstraint* view2WidthToView1Width = [NSLayoutConstraint constraintWithItem:view2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:view1 attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
    
    NSLayoutConstraint* view2RightToViewRight = [NSLayoutConstraint constraintWithItem:view2 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:-30];
    
    NSLayoutConstraint* view2BottomToViewBottom = [NSLayoutConstraint constraintWithItem:view2 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-30];
    
    
    [self.view addConstraints:@[view1TopToViewTop,view1LeftToViewLeft,view1RightToView2Left,view1BottomToViewBottom,view2TopToViewTop,view2RightToViewRight,view2BottomToViewBottom,view2WidthToView1Width]];
    
//    [self.view addConstraints:@[view1TopToViewTop,view1LeftToViewLeft,view1RightToViewRight,view1BottomToViewBottom]];
    
    [self.view layoutIfNeeded];
    
    
    
}

2019-04-12

Theory

关于有navigationbar时self.view问题

  1. 参考链接1
  2. 参考链接2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值