[iOS] 小问题记录

iOS system

iOS version检测

reference

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
   ...
}

文件保存数据库的问题

iOS 往数据库里写保存文件路径的时候,不要写全路径,因为软件更新或者重新安装沙盒路径会变

更新的流程是这样的:更新时,先在新的路径里安装新程序,然后把旧程序文件夹里的配置文件之类的文件拷贝到新的路径里去,然后删除旧程序

所以,如果数据库里保存的是绝对路径,那么软件会找不到文件。所以要保存相对路径。比如/var/mobile/Applications/ECDD1B2D-E53D-4914-BDDB-F0578BADAA38/Documents/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt 只写/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt就好,前半部分用系统方法获取。

保存图片至iPhone图库

reference

UIImageWriteToSavedPhotosAlbum(UIImage *image, 
                               id completionTarget, 
                               SEL completionSelector, 
                               void *contextInfo);

NSString

NSString 和 std::string 相互转换

//NSString to string
NSString *strA = @"NSString";
std::string *strB = new std::string([strA UTF8String]);
//or
std::string strB([strA UTF8String]);

//string to NSString
NSString *str = [NSString stringWithCString:string.c_str() 
                                   encoding:[NSString defaultCStringEncoding]];
NSString *str = [NSString stringWithCString:string.c_str() 
                                   encoding:NSUTF8StringEncoding]; // for chinese


std::string param; // <-- input
NSString* result = [NSString stringWithUTF8String:param.c_str()];
NSString* alternative = [[NSString alloc] initWithUTF8String:param.c_str()];
//chinese
[NSString stringWithCString:m_AnswerSheet.GetName().c_str() encoding:NSUTF8StringEncoding]

NSString实现trimRight方法

参考这里:link reference

//该方法会删除string两端的空格
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

//若要只删除string结尾的空格  写一个NSString拓展类 添加如下方法
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];    
    [self getCharacters:charBuffer];

    for (length; length > 0; length--) {
        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
            break;
        }
    }

    return [self substringWithRange:NSMakeRange(location, length - location)];
}
//然后调用
NSString *trimmedString = [yourString stringByTrimmingTrailingCharactersInSet:[NSCharacterset whitespaceAndNewlineCharacterSet]];

NSString后连接字符串

string = [NSString initWithFormat:@"%@,%@", string1, string2 ];
string = [string1 stringByAppendingString:string2];
string = [string stringByAppendingFormat:@"%@,%@",string1, string2];

NSString,Char,ASCII转换

//char to int ASCII-code
char c = 'a';
int ascii_code = (int)c;

//int to char
int i = 65; // A
c = (char)i;

// NSString to ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65

// ASCII to NSString
int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A

char myChar = 'r';
NSString* string = [NSString stringWithFormat:@"%c" , myChar];

NSString文字高度

reference

cocoa获取UUID

参考:各种OS中生成UUID的方法

NSString CHelpFunction::stringWithUuid() {
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
    CFRelease(uuidObj);
    return uuidString;
}

UIView

UIView贴背景图

UIView只有setBackgroundColor,就用它来设置

UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
[myLabel setBackgroundColor:color];

UIView添加点击事件

参考:reference

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
[preArrowImage setUserInteractionEnabled:YES];
[preArrowImage addGestureRecognizer:singleTap];

-(void)tapDetected{
    NSLog(@"single Tap on imageview");
  }

获取UIView触摸点

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    NSLog(@"x:%f,   y:%f", point.x, point.y);
    if (!CGRectContainsPoint(centerView.frame, point)) {
        [self removeFromSuperview];
    }
}

layoutSubviews调用时机

reference

  • init:不会调用layoutSubviews
  • addSubview::被添加的view1、调用这个方法的view2、view2的所有子view都会调用layoutSubviews
  • setFrame:只有在view设置frame且尺寸参数有不同的情况下调用
  • 滑动UIScrollView时,scrollView和其父view会调用
  • 旋转屏幕会在viewController的根view调用
  • 重新改变view的大小,其父view会调用

drawInRect: withAttributes:的参数怎么写

UIFont *textFont = [UIFont fontWithName: @"Helvetica" size: 60];
UIColor *textColor = [UIColor blackColor];
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;
    
[textContent drawInRect:textRect withAttributes:@{NSFontAttributeName:textFont, NSForegroundColorAttributeName:textColor, NSParagraphStyleAttributeName:textStyle}];

设置粗体文字

首先可以上这个网站:http://iosfonts.com/查看自己要用的字体是否支持粗体,然后使用下面方法 -(void)boldFontForLabel:(UILabel *)label{ UIFont *currentFont = label.font; UIFont *newFont = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold",currentFont.fontName] size:currentFont.pointSize]; label.font = newFont; }

UIView一些尺寸属性

  • frame:origin是相对于屏幕的点的坐标,size就是其尺寸
  • bound: origin永远是(0,0),size也是尺寸
  • center: 是View的中心点,但坐标是相对于屏幕的。如果需要相对自己的中心点,则需要用bound.origin来计算

UIView加外边框

reference

CGFloat borderWidth = 2.0f;

self.frame = CGRectInset(self.frame, -borderWidth, -borderWidth);
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = borderWidth;

UIView切换动画

只要提供View的初识状态和结束状态,然后交给showAnimation来做即可

-(void)showAnimation {

    [self.view addSubview:geopointView]
    geopointView.frame = // somewhere offscreen, in the direction you want it to appear from
    [UIView animateWithDuration:10.0 
                     animations:^{
                         geopointView.frame = // its final location
                     }];
}

UIView滑入动画

reference

[UIView transitionFromView:viewToReplace
                    toView:replacementView
                  duration:1
                   options:UIViewAnimationOptionTransitionFlipFromBottom
                completion:nil];

判断一个点在UIView里

reference

CGPoint locationInView = [imageView convertPoint:point fromView:imageView.window];
if ( CGRectContainsPoint(imageView.bounds, locationInView) ) {
    // Point lies inside the bounds.
}

UIView调用presentViewController

reference

自动布局下获取View的尺寸

reference

把touch事件传递给子View

涉及到事件传递部分内容,另外再开博客记录 reference


UILabel

UILabel设置行间距

reference

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];

label.attributedText = attributedString;

UILabel下划线

reference

NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Test string" 
                                                         attributes:underlineAttribute];

UIButton

模拟按钮点击事件

[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];

UIImage & UIImageView

用纯色生成一个UIImage

reference

@implementation  UIButton (ButtonMagic)

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}

+ (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

UIImage占内存大小

NSUInteger size  = CGImageGetHeight(thumbImage.CGImage) * CGImageGetBytesPerRow(thumbImage.CGImage);

UIImage加边框

reference

把UIView生成UIImage

reference reference2


UIColor

给ClearColor添加alpha

reference

- (void)setBackgroundColor:(UIColor *)color 
{
    self.backgroundColor = [color colorWithAlphaComponent:0.3f];
}

NSNotification

NSNotification流程

//send
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
NSDictionary *d = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_index] forKey:@"index"];
[nc postNotificationName:@"viewClicked" object:self userInfo:d];
//regist observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewClickAt:) name:@"quesViewClicked" object:nil];
//do function
- (void)quesViewClickAt:(NSNotification *)noti {
    int index = [[[noti userInfo] objectForKey:@"index"] intValue];
}
//dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

UITextView & UITextField

keyboard强行关闭

[view endEditing:YES];

UITextView限制输入字符

- (BOOL)textView:(nonnull UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(nonnull NSString *)text {
    // Prevent crashing undo bug 
    if(range.length + range.location > textView.text.length)
    {
        return NO;
    }
    
    NSUInteger newLength = [textView.text length] + [text length] - range.length;
    return newLength <= 1024;
}

UITextView添加默认文字

UITextField是有placeholder(?)这个属性的,但是UITextView没有,大家表示也是醉了。 reference

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"placeholder text here..."]) {
         textView.text = @"";
         textView.textColor = [UIColor blackColor]; //optional
    }
    [textView becomeFirstResponder];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"placeholder text here...";
        textView.textColor = [UIColor lightGrayColor]; //optional
    }
    [textView resignFirstResponder];
}

UITextField光标距离左边间隔太小

UITextField *content = ......;
//设置输入左边距
CGRect frame = content.frame;
frame.size.width = 5;
UIView *leftView = [[UIView alloc] initWithFrame:frame];
content.leftViewMode = UITextFieldViewModeAlways;
content.leftView = leftView;

UITextField下划线

reference

CALayer *border = [CALayer layer];
   CGFloat borderWidth = 2;
   border.borderColor = [UIColor darkGrayColor].CGColor;
   border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
   border.borderWidth = borderWidth;
   [textField.layer addSublayer:border];
   textField.layer.masksToBounds = YES;

UITextField内容改变事件

UITextView有对应的回调,UITextField就没有。 reference reference2

[myTextField addTarget:self 
                action:@selector(textFieldDidChange:) 
      forControlEvents:UIControlEventEditingChanged];

多个UITextField,键盘return改为next->next->done (iOS9又有新的类型)

//set keyboard
if (i == count - 1) 
   [contentText setReturnKeyType:UIReturnKeyDone];
else
   [contentText setReturnKeyType:UIReturnKeyNext];
#pragma mark - TextFieldDelegate
- (BOOL)textFieldShouldReturn:(nonnull UITextField *)textField {
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
    } else {
        // Not found, so remove keyboard.
        [textField resignFirstResponder];
    }
    return NO; // We do not want UITextField to insert line-breaks.
}

UIScrollView & UITableView & UICollectionView

UIScrollView滚动到顶端

//UPDATE FOR iOS 7
[self.scrollView setContentOffset:
    CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
//ORIGINAL
[self.scrollView setContentOffset:CGPointZero animated:YES];
//or if you want to preserve the horizontal scroll position and just reset the vertical position:
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0) animated:YES];

UITableView屏蔽自动滚动效果

reference 继承UITableViewController重写

- (void)viewWillAppear:(BOOL)animated { //不调用super方法  屏蔽自动滚动
    //[super ...];
}

判断UITableViewCell是否可见

reference

-(BOOL)isRowZeroVisible {
  NSArray *indexes = [tableView indexPathsForVisibleRows];
  for (NSIndexPath *index in indexes) {
    if (index.row == 0) {
      return YES;
    }
  }

  return NO;
}

UICollectionViewCell构造

UICollectionViewCell 不能用-(id)init{},要用-(id)initWithFrame:(CGRect)frame或者initWithCoder()


NSArray & NSDictionary

NSArray和std::vector转换

std::vector<std::string> strVec;
for (int i = 0; i < [NSMutableArrayObject count]; i++) {
   NSString *NS_Ans = (NSString *)[NSMutableArrayObject objectAtIndex:i];
   std::string Str_Ans = *new std::string([NS_Ans UTF8String]);
   strVec.push_back(Str_Ans);
}
return strVec;
//
std::vector<std::string> ansArray = getOneVector();           
NSMutableArray *nsArray = [NSMutableArray array];
for (int j = 0; j < ansArray.size(); j++) {
   NSString *item = [NSString stringWithCString:ansArray[j].c_str() encoding:[NSString defaultCStringEncoding]];         
   [nsArray addObject:item];
}
return ansArray;

NSArray添加CGPoint对象

一般使用NSValue reference

NSArray *points = [NSArray arrayWithObjects:
                     [NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)],
                     [NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)],
                     nil];
                     
NSValue *val = [points objectAtIndex:0];
CGPoint p = [val CGPointValue];

NSMutableArray/NSMutableDictionary插入空值

if ((NSNull *)[mPages objectAtIndex:showPos] == [NSNull null]) {
        [mPages removeObjectAtIndex:showPos];
}
[mPages insertObject:mPage atIndex:showPos];

[mPages removeObjectAtIndex:hidePos];
[mPages insertObject:[NSNull null] atIndex:hidePos];

NSDictionary保存int类型

NSDictionary保存的都是对象,所以int要转成NSNumber

//save
[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_quesIndex] forKey:@"index"];
//get
i = [[dic objectForKey:@"index"] intValue];

其他

Cocoapods pod install 太慢

reference

pod install --verbose --no-repo-update

标注代码段

reference 在OC里经常用

#pragma mark - xxxx

来分隔代码 Swift里用的是

// MARK: - xxx

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏王大锤

iOS8 自定义navigationbar 以及 UIBarButtonItem 边距问题

3117
来自专栏coding...

iOS开发实战-时光记账Demo 本地数据库版效果分析Demo地址

由于主页只是一个展示的时光轴界面,UIScrollView加几个按钮就能完成,需要读取数据库内容,所以我们先把内页-增加账单 完成。

1132
来自专栏Alice

ios textView跟随键盘的移动

实现效果: textview 能够跟随键盘的移动而移动 效果图如下: ? ? 下边贴上主要的代码: 1.创建textview @interface ViewCo...

2815
来自专栏ios 技术积累

Objective-C UIButton 自定义图片位置

在项目中经常会遇到一个按钮上放一个图片 位置有可能会是在标题的上,下,左,右 如果一个按钮,可以单独设置titleEdgeInsets和imageEdgeIn...

1923
来自专栏TechBox

史上最全的iOS之UITextView实现placeHolder占位文字的N种方法前言方法一方法二方法三方法四方法五

2023
来自专栏coding...

iOS开发-RAC+MVVM练手项目 图床App写在前面准备工作界面设计首页历史关于后记

前段时间闲着无聊和盆友就搞了个图床站Chevereto-Free,忽然发现居然有API提供,而且很简单,只需要一个KEY就可以

1102
来自专栏一“技”之长

iOS开发一款小巧简洁的日历控件 原

        日 历是iOS开发中有时会用到的一个UI控件,网上开源的代码也很多,我浏览过一些,大致有两种模式,一种是日历的逻辑由开发者自己实现,通过计算闰年...

3662
来自专栏Python疯子

Swift -标签页控制器(UITabBarController)用法

Simulator Screen Shot 2016年11月8日 19.11.36.png

5222
来自专栏DannyHoo的专栏

iOS开发中使用CIFilter生成二维码和条形码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010105969/article/details/...

1781
来自专栏刘晓杰

RN实现ListView

4009

扫码关注云+社区

领取腾讯云代金券