Category: iOS

  • How to get a particular key for object in NSDictionary

    This is how you can get a first key for object (in case it is NSString):

    NSArray *keys = [yourDic allKeysForObject:yourObject];
    NSString *yourKey;
    if ([keys count] > 0) 
       yourKey = keys[0];
    

    Since you may not get a key for some objects, if it is absent.

  • How to switch off UIWebView caching in iOS

    I found how to clear cache, before app starts. Add this in didFinishLaunchingWithOptions:

    [[NSURLCache sharedURLCache] removeAllCachedResponses];

    It is possible to remove Cookies and cache for one request. Read it here.

  • How to add an array to the top of another array in iOS

    I found two good solutions in StackOverflow:

    [existingArray replaceObjectsInRange:NSMakeRange(0,0)
                    withObjectsFromArray:newArray];
    

    And the second one:

    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange: (NSRange) {0, [newArray count]}];
    [existingArray insertObjects: newArray atIndexes: indexes];
    
  • Get file size using NSFileManager

    To get file size in bytes using NSFileManager do the following:

    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil];
    _size = [attrs fileSize];
    
  • How to add photos to iOS simulator

    This solution worked for me under iOS 6.1:

    Close the simulator if it is running xcode project.
    Run simulator from the dock by clicking on it.
    Drag & drop the image into simulator.
    Tap and hold the image (opened in safari) and select the save option.
    You are done.

    Taken from here.

  • UITextField edge insets

    To change edge insets in UITextField, create a new subclass and override these methods:

    // placeholder position
    - (CGRect)textRectForBounds:(CGRect)bounds {
        return CGRectInset(bounds, 0, 10);
    }
    
    // text position
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return CGRectInset(bounds, 0, 10);
    }
    

    Here 0 is dx, 10 is dy.

    Found this nice solution here

  • How to make UITextField in UITableView become first responder

    I loadView create a UITextField ivar.

    - (void)loadView
    {
        [super loadView];
    
        _userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 10, 280, 30)];
        _userNameTextField.placeholder = @"Введите имя пользователя";
        [_userNameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        _userNameTextField.returnKeyType = UIReturnKeyGo;
        _userNameTextField.delegate = self;
        _userNameTextField.tag = 1;
    ...
    

    In ViewDidAppear make it first responder:

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        
        [_userNameTextField becomeFirstResponder];
    }
    

    In cellForRow add it as a subview:

    - (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                [cell addSubview:_userNameTextField];
    
  • Отлавливание Shake событий на iOS

    Взять любое кастмное View на данном экране. Добавить в его коде:

    - (BOOL)canBecomeFirstResponder
    {
        return YES; // Для отлавления Shake события
    }
    

    При загрузке данного View Controller и инциализации данного View делать следующее:

    [_composeButton becomeFirstResponder]; // Для отлавления Shake события
    

    Добавить следующий метод в данном View Controller.

    // Для отлавления Shake события
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        // Обработка события встряхивания
        if ( event.subtype == UIEventSubtypeMotionShake ) {
            NCLog(@"Shaked");
            
            if ( UD_BOOL(UDKeyNewMessageOnShake) ) [self showComposeEmailViewControllerInMode:kComposeModeNew WithMCMessageFromIndexPath:nil];
        }
    }
    

    Все!

  • performSelector may cause a leak because its selector is unknown

    This is very popular question in StackOverflow.

    However, the best answer for XCode 4.6 is this:
    “In your project Build Settings, under Other Warning Flags (WARNING_CFLAGS), add
    -Wno-arc-performSelector-leaks

    Now just make sure that the selector you are calling does not cause your object to be retained or copied.”

    “Note you can add the same flag for specific files rather than the entire project. If you look under Build Phases->Compile Sources, you can set per file Compiler Flags (just like you want to do for excluding files from ARC). In my project just one file should use selectors this way, so I just excluded it and left the others.”

    Code snippet:

    -Wno-arc-performSelector-leaks
    
  • Subclassing UIButton (Composition over inheritance example)

    I have created a custom class, preferring composition over inheritance and it works perfect. My custom class has a button and it knows it’s MCContact object. Also it draws a proper button and calculates frames automatically using MCContact object, that is passed.

    Header file sample:

    #import 
    
    @protocol MCContactViewDelegate;
    
    @interface MCContactView : UIView
    {
    
    }
    
    @property (nonatomic, strong) MCContact *mcContact;
    @property (nonatomic, weak) id <MCContactViewDelegate> delegate;
    
    - (id)initWithContact:(MCContact*)mcContact delegate:(id <MCContactViewDelegate>)delegate;
    
    @end
    
    @protocol MCContactViewDelegate 
    
    - (void)contactViewButtonClicked:(MCContactView*)contactView;
    
    @end
    

    Implementation file:

    #import "MCContactView.h"
    
    @interface MCContactView()
    {
        UIButton *_button;
    }
    
    @end
    
    @implementation MCContactView
    
    - (id)initWithContact:(MCContact*)mcContact delegate:(id <MCContactViewDelegate>)delegate
    {
        self = [super initWithFrame:CGRectZero];
        
        if (self) {
            
            GetTheme();
            
            _mcContact = mcContact;
            _delegate = delegate;
            _button = [UIButton buttonWithType:UIButtonTypeCustom];
            
            UIImage *normalBackgroundImage = [[UIImage imageNamed:@"tokenNormal.png"] stretchableImageWithLeftCapWidth:12.5 topCapHeight:12.5];
            [_button setBackgroundImage:normalBackgroundImage forState:UIControlStateNormal];
            
            UIImage *highlightedBackgroundImage = [[UIImage imageNamed:@"tokenHighlighted.png"] stretchableImageWithLeftCapWidth:12.5 topCapHeight:12.5];
            [_button setBackgroundImage:highlightedBackgroundImage forState:UIControlStateHighlighted];
            
            _button.titleLabel.font = [theme contactButtonFont];
            [_button setTitleColor:[theme contactButtonTextColor] forState:UIControlStateNormal];
            
            [_button setTitleEdgeInsets:UIEdgeInsetsMake(4, 6, 4, 6)];
            
            NSString *tokenString = ([allTrim(mcContact.name) length]>0) ? mcContact.name : mcContact.eMail;
            [_button setTitle:tokenString forState:UIControlStateNormal];
            
            [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            CGSize size = [tokenString sizeWithFont:[theme contactButtonFont]];
            size.width += 20;
            if (size.width > 200) {
                size.width = 200;
            }
            size.height = normalBackgroundImage.size.height;
            [_button setFrame:CGRectMake(0, 0, size.width, size.height)];
            
            self.frame = _button.frame;
            [self addSubview:_button];
        }
        
        return self;
    }
    
    
    - (void)buttonClicked:(id)sender
    {
        [self.delegate contactViewButtonClicked:self];
    }
    
    @end