IOS开发基础知识--碎片37
1:iOS 使用NJKWebViewProgress做webview进度条
引入头文件: #import "NJKWebViewProgressView.h" #import "NJKWebViewProgress.h"
遵守协议 <UIWebViewDelegate, NJKWebViewProgressDelegate> 实现代码 @implementation ViewController { IBOutlet __weak UIWebView *_webView; NJKWebViewProgressView *_webViewProgressView; NJKWebViewProgress *_webViewProgress; } - (void)viewDidLoad { [super viewDidLoad]; _webViewProgress = [[NJKWebViewProgress alloc] init]; _webView.delegate = _webViewProgress; _webViewProgress.webViewProxyDelegate = self; _webViewProgress.progressDelegate = self; CGRect navBounds = self.navigationController.navigationBar.bounds; CGRect barFrame = CGRectMake(0, navBounds.size.height - 2, navBounds.size.width, 2); _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame]; _webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; [_webViewProgressView setProgress:0 animated:YES]; [self loadBaidu]; [self.navigationController.navigationBar addSubview:_webViewProgressView]; } -(void)loadBidu { NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.baidu.com/"]]; [_webView loadRequest:req]; } #pragma mark - NJKWebViewProgressDelegate -(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress { [_webViewProgressView setProgress:progress animated:YES]; self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"]; }
2:解决输入框UITextField关于拼音或部首被当作内容响应
// 添加监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChanged:) name:UITextFieldTextDidChangeNotification object:self.textField]; // 监听处理 - (void)textFieldDidChanged:(NSNotification *)notification { NSString *text = self.textField.text; // 拼音输入时,拼音字母处于选中状态,此时不判断是否超长 UITextRange *selectedRange = [self.textField markedTextRange]; if (!selectedRange || !selectedRange.start) { if (text.length > MAXLENGTH) { self.textField.text = [text substringToIndex:MAXLENGTH]; } } }
这里主要使用了两个知识:
- 输入法输入时,拼音字母或者笔画处于选中状态,可以使用 markedTextRange 获取到
- 普通输入,以及将输入法的待选字填入输入框时,都会发出 UITextFieldTextDidChangeNotification, 可以监听这个通知,并事后对 UITextField 的内容做清理
另外除了使用监听 NSNotification 的方式,也可以使用 addTargetAction 的方式,代码如下:
[self.textField addTarget:self
action:@selector(textChange:)
forControlEvents:UIControlEventEditingChanged];
这与上面的方式是等价的,但是使用 NSNotification 需要在对象销毁时 removeObserver,而这种方式不需要
3:根据内容自适应UIButton的大小
NSString *str = @"这是按钮的标题"; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.titleLabel.font = [UIFont systemFontOfSize:13.0]; //对按钮的外形做了设定,不喜可删~ btn.layer.masksToBounds = YES; btn.layer.borderWidth = 1; btn.layer.borderColor = [[UIColor blackColor] CGColor]; btn.layer.cornerRadius = 3; [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn setTitle:str forState:UIControlStateNormal]; //重要的是下面这部分哦! CGSize titleSize = [str sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:btn.titleLabel.font.fontName size:btn.titleLabel.font.pointSize]}]; titleSize.height = 20; titleSize.width += 20; btn.frame = CGRectMake(100, 100, titleSize.width, titleSize.height); [view addSubview:btn];
4:解决部分文字样式不同的方法
NSRange range = [title rangeOfString:targetname]; NSMutableAttributedString *mutableTitle = [[NSMutableAttributedString alloc] initWithString:title]; [mutableTitle addAttribute:NSForegroundColorAttributeName value:COLOR_WORD_GRAY_2 range:NSMakeRange(0, title.length)]; if (range.length>0) { [mutableTitle addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0xf7ab00) range:range]; NSInteger startIndex = range.location+range.length; [mutableTitle addAttribute:NSForegroundColorAttributeName value:COLOR_WORD_GRAY_2 range:NSMakeRange(startIndex, title.length-startIndex)]; [mutableTitle addAttribute:NSFontAttributeName value:CHINESE_SYSTEM(16) range:NSMakeRange(0, title.length)]; } self.titleLabel.attributedText=mutableTitle;
5:Masonry scrollview循环布局
@interface ScrollViewController () @property (nonatomic, strong) UIScrollView *scrollView; @end @implementation ScrollViewController - (void)viewDidLoad { [super viewDidLoad]; self.scrollView = [[UIScrollView alloc] init]; self.scrollView.pagingEnabled = NO; [self.view addSubview:self.scrollView]; self.scrollView.backgroundColor = [UIColor lightGrayColor]; CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width; UILabel *lastLabel = nil; for (NSUInteger i = 0; i < 20; ++i) { UILabel *label = [[UILabel alloc] init]; label.numberOfLines = 0; label.layer.borderColor = [UIColor greenColor].CGColor; label.layer.borderWidth = 2.0; label.text = [self randomText]; // We must preferredMaxLayoutWidth property for adapting to iOS6.0 label.preferredMaxLayoutWidth = screenWidth - 30; label.textAlignment = NSTextAlignmentLeft; label.textColor = [self randomColor]; [self.scrollView addSubview:label]; [label mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(15); make.right.mas_equalTo(self.view).offset(-15); if (lastLabel) { make.top.mas_equalTo(lastLabel.mas_bottom).offset(20); } else { make.top.mas_equalTo(self.scrollView).offset(20); } }]; lastLabel = label; } [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(self.view); // 让scrollview的contentSize随着内容的增多而变化 make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20); }]; } - (UIColor *)randomColor { CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0 CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; } - (NSString *)randomText { CGFloat length = arc4random() % 50 + 5; NSMutableString *str = [[NSMutableString alloc] init]; for (NSUInteger i = 0; i < length; ++i) { [str appendString:@"测试数据很长,"]; } return str; } @end
6:Masonry remake更新约束
@interface RemakeContraintsController () @property (nonatomic, strong) UIButton *growingButton; @property (nonatomic, assign) BOOL isExpanded; @end @implementation RemakeContraintsController - (void)viewDidLoad { [super viewDidLoad]; self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem]; [self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal]; self.growingButton.layer.borderColor = UIColor.greenColor.CGColor; self.growingButton.layer.borderWidth = 3; self.growingButton.backgroundColor = [UIColor redColor]; [self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.growingButton]; self.isExpanded = NO; } - (void)updateViewConstraints { // 这里使用update也是一样的。 // remake会将之前的全部移除,然后重新添加 [self.growingButton mas_remakeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(0); make.left.right.mas_equalTo(0); if (self.isExpanded) { make.bottom.mas_equalTo(0); } else { make.bottom.mas_equalTo(-350); } }]; [super updateViewConstraints]; } - (void)onGrowButtonTaped:(UIButton *)sender { self.isExpanded = !self.isExpanded; if (!self.isExpanded) { [self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal]; } else { [self.growingButton setTitle:@"点我收起" forState:UIControlStateNormal]; } // 告诉self.view约束需要更新 [self.view setNeedsUpdateConstraints]; // 调用此方法告诉self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用 [self.view updateConstraintsIfNeeded]; [UIView animateWithDuration:0.3 animations:^{ [self.view layoutIfNeeded]; }]; } @end
7:UIPickerView的运用
引入<UIPickerViewDataSource, UIPickerViewDelegate> 初始化: self.pickArrayData=@[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7"]; if (!self.myPickView) { self.myPickView=[[UIPickerView alloc]init]; self.myPickView.showsSelectionIndicator=YES; self.myPickView.dataSource = self; self.myPickView.delegate = self; [self addSubview:self.myPickView]; [self.myPickView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(0); make.right.mas_equalTo(0); make.top.mas_equalTo(self.topView.bottom).with.offset(40); make.height.mas_equalTo(100); }]; } #pragma mark UIPickerViewDataSource, UIPickerViewDelegate // pickerView 列数 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 5; } // pickerView 每列个数 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return self.pickArrayData.count; } // 每列宽度 - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return (SCREEN_WIDTH-40)/5; } // 返回选中的行 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"%ld-%@",(long)component,[self.pickArrayData objectAtIndex:row]); } //返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上 -(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [self.pickArrayData objectAtIndex:row]; } 获取选中的内容: -(void)confirmAction { NSMutableString *result=[[NSMutableString alloc]init];; NSInteger row1=[self.myPickView selectedRowInComponent:0]; if (row1!=0) { [result appendFormat:@"%@房",[self.pickArrayData objectAtIndex:row1]]; } NSInteger row2=[self.myPickView selectedRowInComponent:1]; if (row2!=0) { [result appendFormat:@"%@厅",[self.pickArrayData objectAtIndex:row2]]; } NSInteger row3=[self.myPickView selectedRowInComponent:2]; if (row3!=0) { [result appendFormat:@"%@卫",[self.pickArrayData objectAtIndex:row3]]; } NSInteger row4=[self.myPickView selectedRowInComponent:3]; if (row4!=0) { [result appendFormat:@"%@厨",[self.pickArrayData objectAtIndex:row4]]; } NSInteger row5=[self.myPickView selectedRowInComponent:4]; if (row5!=0) { [result appendFormat:@"%@阳台",[self.pickArrayData objectAtIndex:row5]]; } self.selectedResult=[NSString stringWithString:result]; if (self.confirmButtonBlock) { self.confirmButtonBlock(self.selectedResult); } }
8:汉字转为拼音
- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst { //转成了可变字符串 NSMutableString *str = [NSMutableString stringWithString:aString]; //先转换为带声调的拼音 CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO); //再转换为不带声调的拼音 CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString *pinYin = [str capitalizedString]; //转化为大写拼音 if(isGetFirst) { //获取并返回首字母 return [pinYin substringToIndex:1]; } else { return pinYin; } }