iOS開發過程中常用代碼


1.訪問相機相冊

#pragma mark 拍照
- (void)takePhoto {
if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; //是否可編輯
//攝像頭
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:nil];

AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
//無權限
UIAlertController *alert = [YLAlertController createOneButtonAlertViewWithTitle:nil message:@"請在iPhone的\"設置-隱私\"選項中,允許迪動訪問你的攝像頭" buttonTitle:@"確定" buttonAction:nil];
[picker presentViewController:alert animated:YES completion:nil];
}
}
}

#pragma mark 從相冊選擇
- (void)chooseFromAlbum {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
//打開相冊選擇照片
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
}

#pragma mark 相機相冊選擇后的代理事件,image即為選擇的圖片對象
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//得到圖片
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil];
}

 2.自己封裝的網絡請求的調用

 NSDictionary *parameters = @{
@"uid":USER_ID,
@"token":USER_CURRENT_TOKEN,
};
[[NetRequest sharedRequest] postURL:[<#請求地址#> getFullRequestPath] parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"請求結果是%@",responseObject);
if ([responseObject isRequestSuccess]) {

} else {
HUD_TEXTONLY([responseObject requestErrorInfo]);
}
} failed:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
HUD_FAILED(REQUEST_FAILED_INFO);
}];

 3.注冊鍵盤彈出和消失的通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

#pragma mark 鍵盤的通知
- (void)keyboardWillShow:(NSNotification *)noti {
NSDictionary *dict = noti.userInfo;
NSValue *frameValue = [dict valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect frame = [frameValue CGRectValue];
CGFloat height = frame.size.height;
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
}

- (void)keyboardWillHide:(NSNotification *)noti {
self.tableView.contentInset = UIEdgeInsetsZero;
}

 4.設置tableView

- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
}];

_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{

}];

[self.view addSubview:_tableView];
[_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
}
return _tableView;
}


#pragma mark UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return <#NSInteger#>;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return <#NSInteger#>;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuseIdentifier = @"";
<#UITableViewCell#> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell) {
cell = [[<#UITableViewCell#> alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return <#expression#>;
}

 5.獲取當前的年月日等

    NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear |
NSCalendarUnitMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute |
NSCalendarUnitSecond | NSCalendarUnitWeekday;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
NSInteger year = [dateComponent year];
NSInteger month = [dateComponent month];

 6.UITableView嵌套UITextView時無法通過修改tableView的contentInset來讓tableView自動上移,避免鍵盤遮擋textView,可用下面方法解決#pragma mark 鍵盤的通知

#pragma mark 鍵盤的通知
- (void)keyboardWillShow:(NSNotification *)noti {

NSDictionary *dict = noti.userInfo;
NSValue *frameValue = [dict valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect frame = [frameValue CGRectValue];
CGFloat height = frame.size.height;
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
if ([_explainTextView isFirstResponder]) {
//將textView的frame轉換為相對於tableView的frame
CGRect frame1 = [_explainTextView convertRect:_explainTextView.frame toView:self.tableView];
//height為鍵盤高度,(SCREEN_HEIGHT - 64 - frame1.origin.y - frame1.size.height)為textView底邊距離屏幕底邊的高度
self.tableView.contentOffset = CGPointMake(0, height - (SCREEN_HEIGHT - 64 - frame1.origin.y - frame1.size.height));
}
}

- (void)keyboardWillHide:(NSNotification *)noti {
self.tableView.contentInset = UIEdgeInsetsZero;
}

 7.限制金額輸入的方法

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet
*cs = [[NSCharacterSet characterSetWithCharactersInString:@".0123456789"] invertedSet];
NSString
*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest
= [string isEqualToString:filtered];
if(!basicTest) {
return NO;
}
else {
if ([string isEqualToString:@"."]) {
if ([textField.text isEqualToString:@""]) {
textField.text
= @"0.";
return NO;
}
else if ([textField.text containsString:@"."]) {
return NO;
}
}
NSRange myRange
= [textField.text rangeOfString:@"."];
if (myRange.length != 0) {
if ([textField.text length]-myRange.location >= 3) {
if ([string isEqualToString:@""]) {
return YES;
}
else {
return NO;
}
}
else {
return YES;
}
}
else {
return YES;
}
}
}

 

 8.UITextField密文輸入時再次編輯內容不清空

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//得到輸入框的內容
NSString * textfieldContent = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.passwordTextField && textField.isSecureTextEntry ) {
textField.text = textfieldContent;
return NO;
}
return YES;
}

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com