Blog

  • 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
    
  • App Link in iTunes Store

    Use this tool to create links:

    http://itunes.apple.com/linkmaker/

    It can create links for iPhone and iPad apps and your catalog.

  • Determine if device is iPhone 5

    This is how you determine, if device has a screen size of iPhone 5 if you develop an app for iPhones only.

    #define IS_WIDESCREEN [[UIScreen mainScreen] bounds].size.height >= 568

    Here is much more complex way to determine this.

  • Delete all .svn folders in project directory on Mac

    In terminal in project directory:

    find ./ -name ".svn" | xargs rm -Rf

    Read here about xargs.

  • dispatch_after code sample

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        <#code to be executed on the main queue after delay#>
    });

    Apple GCD Reference