·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> [随时更新][iOS]小问题记录

[随时更新][iOS]小问题记录

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

本文地址转载请保留:http://www.cnblogs.com/rossoneri/p/4708027.html

1. NSString and std::string convert to each other

//from stackoverflow
//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]
//this removes white space from both ends of a string
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//just wanna remove white space at the end of the string? read the link above for more detail.

3. convert std::vector and NSArray to each other

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;            

4. NSString append

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

5. Get uuid in cocoa .reference from 各种OS中生成UUID的方法

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

6. set UIView background image

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

7. set UIImage a click event, suitable for other uiview i think. 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");
  }

8. save int value in nsdictionary

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

9. 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];
}

10. force close keyboard

[view endEditing:YES]; 

11. remove all subviews

NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}

12. limit the input

- (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;
}

13. insert null object into NSMutableArray or NSMutableDictionary etc.

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

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

14. UIScrollView scoll to top

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];
UITextField *content = ......;
//设置输入左边距
CGRect frame = content.frame;
frame.size.width = 5;
UIView *leftView = [[UIView alloc] initWithFrame:frame];
content.leftViewMode = UITextFieldViewModeAlways;
content.leftView = leftView;

16. 多个UITextField,键盘return 改为 next->next->done

//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.
}

17. ios系统号detect

#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")) {
   ...
}

18. 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}];

19. 设置粗体文字

首先可以上这个网站: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;
}

20. 文件保存数据库的问题

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就好,前半部分用系统方法获取。

21. get UIView touch point

- (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];
    }
    
}

22. UIView一些尺寸属性

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

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

autolayout
[tmpView addSubview:m_textLeftTime];
[m_textLeftTime setTranslatesAutoresizingMaskIntoConstraints:NO];

[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[m_imgClock]-0-[m_textLeftTime]"
                                                                options:0
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(m_imgClock, m_textLeftTime)]];

[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[tmpView]-(<=1)-[m_imgClock(==32)]"
                                                                options:NSLayoutFormatAlignAllCenterY
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(tmpView, m_imgClock)]];

[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[tmpView]-(<=1)-[m_textLeftTime]"
                                                                options:NSLayoutFormatAlignAllCenterY
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(tmpView, m_textLeftTime)]];

memcmp(&(GetClientID()), &(mClientID), sizeof(mClientID)) compare unsigned char or other