понедельник, 19 августа 2013 г.

IOS how to trim string

Для того чтобы обрезать у строки пустые места справа и слева необходимо выполнить следующее

NSString *str= [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmedStr = [str stringByTrimmingCharactersInSet:whitespace];

Reset UITextField's original placeholder text

Для того чтобы обрабатывать события связанные с вводом сиволов в текстовое поле, необходимо чтобы ваш ViewController был делегатом  UITextFieldDelegate

@interface ViewController : UIViewController<UITextFieldDelegate> 

Для обработки появление и исчезновения placeholder'а необходимо реализовать два метода из UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = nil;
}
 
- (void)textFieldDidEndEditing:(UITextField *)textField {
    textField.placeholder = @"Your Placeholdertext";
}

воскресенье, 18 августа 2013 г.

Method overloading in Objective-C

Objective-C не поддерживает перегрузку методов, так что необходимо использовать различные имена при создании методов. Однако заметим, что имя метода включает в себя сигнатуру ключевых слов (имена параметров, которые идут до ":"), так что два следующих метода будут разными, несмотря на то, что они оба начинаются с "writeToFile"

-(void) writeToFile:(NSString *)path fromInt:(int)anInt;
-(void) writeToFile:(NSString *)path fromString:(NSString *)aString;

Имена двух методов: "writeToFile:fromInt:" и "writeToFile:fromString:"

Categories. UIColor from Hex and from RGB

Цвет может задаваться через шестнадцатиричную запись или через RGB. Для того, чтобы создать нужный нам цвет, зная только его шестнадцатиричное значение, необходимо создать так называемую категорию. Категория позволяет добавить к существующим классам новые методы. То есть мы добавим к классу UIColor методы которые позволят создавать цвет, используя шестнадцатиричную запись или RGB значение цвета.

UIColor+Hex.h

#import <UIKit/UIKit.h>
 
@interface UIColor (Hex)
 
+ (UIColor *) colorWithHexString:(NSString *)aHexString;
 
+ (UIColor *) colorWithRGBHex:(UInt32)aHex;
 
@end


UIColor+Hex.m

#import "UIColor+Hex.h"
 
@implementation UIColor (Hex)
 
+ (UIColor *) colorWithHexString:(NSString *)aHexString
{
    NSScanner *scanner = [NSScanner scannerWithString:aHexString];
    unsigned hexNum;
 
    if (![scanner scanHexInt:&hexNum])
    {
        return nil;
    }
 
    return [UIColor colorWithRGBHex:hexNum];
}
 
+ (UIColor *) colorWithRGBHex:(UInt32)aHex
{
    int r = (aHex >> 16) & 0xFF;
    int g = (aHex >> 8) & 0xFF;
    int b = (aHex) & 0xFF;
 
    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:1.0f];
}
 
@end

Использование метода категории UIColor+Hex

UIColor *color = [UIColor colorWithHexString:@"c90606"];

UITextView with placeholder

Стандартный компонент UITextView не имеет placeholder, поэтому следует разработать подкласс этого компонента, который бы имел placeholder.

UIPlaceHolderTextView.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
 
 
@interface UIPlaceHolderTextView : UITextView {
    NSString *placeholder;
    UIColor *placeholderColor;
 
@private
    UILabel *placeHolderLabel;
}
 
@property (nonatomic, retain) UILabel *placeHolderLabel;
@property (nonatomic, retain) NSString *placeholder;
@property (nonatomic, retain) UIColor *placeholderColor;
 
-(void)textChanged:(NSNotification*)notification;
 
@end

UIPlaceHolderTextView.m

#import "UIPlaceHolderTextView.h"
 
 
@implementation UIPlaceHolderTextView
 
@synthesize placeHolderLabel;
@synthesize placeholder;
@synthesize placeholderColor;
 
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
#if __has_feature(objc_arc)
#else
    [placeHolderLabel release]; placeHolderLabel = nil;
    [placeholderColor release]; placeholderColor = nil;
    [placeholder release]; placeholder = nil;
    [super dealloc];
#endif
 
}
 
- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setPlaceholder:@""];
    [self setPlaceholderColor:[UIColor lightGrayColor]];
    [[NSNotificationCenter defaultCenter] addObserver:self 
      selector:@selector(textChanged:) 
      name:UITextViewTextDidChangeNotification object:nil];
}
 
- (id)initWithFrame:(CGRect)frame
{
    if( (self = [super initWithFrame:frame]) )
    {
        [self setPlaceholder:@""];
        [self setPlaceholderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self 
          selector:@selector(textChanged:) 
          name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}
 
- (void)textChanged:(NSNotification *)notification
{
    if([[self placeholder] length] == 0)
    {
        return;
    }
 
    if([[self text] length] == 0)
    {
        [[self viewWithTag:999] setAlpha:1];
    }
    else
    {
        [[self viewWithTag:999] setAlpha:0];
    }
}
 
- (void)setText:(NSString *)text {
    [super setText:text];
    [self textChanged:nil];
}
 
- (void)drawRect:(CGRect)rect
{
    if( [[self placeholder] length] > 0 )
    {
        if ( placeHolderLabel == nil )
        {
            placeHolderLabel = [[UILabel alloc] 
              initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
            placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            placeHolderLabel.numberOfLines = 0;
            placeHolderLabel.font = self.font;
            placeHolderLabel.backgroundColor = [UIColor clearColor];
            placeHolderLabel.textColor = self.placeholderColor;
            placeHolderLabel.alpha = 0;
            placeHolderLabel.tag = 999;
            [self addSubview:placeHolderLabel];
        }
 
        placeHolderLabel.text = self.placeholder;
        [placeHolderLabel sizeToFit];
        [self sendSubviewToBack:placeHolderLabel];
    }
 
    if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
    {
        [[self viewWithTag:999] setAlpha:1];
    }
 
    [super drawRect:rect];
}
 
@end

UITableViewCell, show delete button on swipe

В таблице UITableView есть такая штука, когда проводишь пальцем по строке, то появляется кнопка удалить. Как сделать чтобы эта кнопка появлялась или не появлялась и как обрабатывать нажатие на кнопку удалить.

// Override to support conditional editing of the table view.
// This only needs to be implemented if you are going to be returning NO
// for some items. By default, all items are editable.
- (BOOL)tableView:(UITableView *)tableView 
  canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}
 
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView 
  commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
  forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

четверг, 15 августа 2013 г.

Proper URL encoding


При передаче параметров в строке URL в iOS могут возникнуть проблемы с формированием правильной строки адреса  URL. Причиной этого могут быть не правильно закодированные символы в адресе, например пробелы. Чтобы этого избежать необходимо кодировать строку адреса. Закодировать строку которая будет использоваться в качестве URL в iOS очень просто. Для этого достаточно выполнить лишь один метод, который преобразует незакодированную строку в закодированную.

Непосредственно сам метода кодировки
NSString *fullUrlString = [loginUrlString stringByAppendingString:params];
 
NSString *properlyEscapedURL = 
  [fullLoginUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Пример применения метода кодировки
NSString *urlString = @"/rest/resource/method";
 
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
 
NSDateFormatter *dateFormatterForSecondDate = 
  [[[NSDateFormatter alloc] init] autorelease];
 
[dateFormatterForSecondDate setDateFormat:@"dd.MM.yyyy HH:mm"];
 
NSString *userIdStr = [currentUserIdNumber stringValue];
 
NSString *userIdParam = [@"?userId=" stringByAppendingString:userIdStr];
 
NSString *fromCityParam = [@"&fDispCity=" stringByAppendingString:fromCity];
 
NSString *toCityParam = [@"&fDeliveryCity=" stringByAppendingString:toCity];
 
NSString *fromDateParam = 
  [@"&fDate=" stringByAppendingString:[dateFormatter stringFromDate:fromDate]];
 
NSString *weightParam = [@"&fTruckCategory=" stringByAppendingString:
  [MyEnums getNameForTruckCategory:truckCategory]];
 
NSString *toDateParam = [@"&fDateAlong=" stringByAppendingString:
  [dateFormatterForSecondDate stringFromDate:toDate]];
 
NSMutableString *params = [NSMutableString stringWithString:userIdParam];
[params appendString:fromCityParam];
[params appendString:toCityParam];
[params appendString:fromDateParam];
[params appendString:weightParam];
[params appendString:toDateParam];
 
NSString *fullUrlString = [loginUrlString stringByAppendingString:params];
 
NSString *properlyEscapedURL = 
  [fullLoginUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
NSURL *url = [NSURL URLWithString:properlyEscapedURL];

String representation of NSDate

Для того чтобы получить строковое представление даты необходимо вызывать метод description класса NSDate

NSDate* currentDate = [NSDate date];
 
NSString* dateInString = [currentDate description];

NSDateFormatter example

Как преобразовать объект класса NSDate в строку и при этом получить нужные нам составляющие даты. Для этого нужно использовать класс  NSDateFormatter и с помощью этого класса задать нужный нам формат даты.

NSDate *currentDateTime = [NSDate date];
 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
 
NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
 
NSLog(@"%@", dateInStringFormated);
 
[dateFormatter release]; 

Set the time to date

Для манипуляций с датой необходимо использовать классы NSDateComponents и NSCalendar. Напрмер, ниже показано как задать сегодняшней дате определенное время - 23 часа 59 минут.

NSDate *now = [NSDate date];
NSCalendar *calendar = [[[NSCalendar alloc] 
  initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:
  NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
  fromDate:now];
[components setHour:23];
[components setMinute:59];
NSDate *today23h59m = [calendar dateFromComponents:components];

вторник, 13 августа 2013 г.

UIScrollView scroll to top programmatically

Программно перемотать область прокрутки наверх можно двумя способами

Первый
[self.scrollView setContentOffset:CGPointZero animated:YES];

Второй
[self.scrollView 
  setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0) 
  animated:YES];

понедельник, 12 августа 2013 г.

How to add a UIButton in the header of UITableView header

Для добавления кнопки в заголовок таблицы вам необходимо использовать методы делегаты класса UITableView

Метод, в котором указываем высоту View, которую мы будем вставлять в заголовок
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

Метод, в котором определяем View и содержащуюся в ней кнопку
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Пример добавления кнопки в заголовок таблицы
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
 
    return 58;
 
}
 
 
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
 
    UIView *customView = [[[UIView alloc] 
      initWithFrame:CGRectMake(10.0, 0.0, self.view.bounds.size.width, 53.0)] 
      autorelease];
 
    CustomGradientButon *changeConditionsButton = 
      [[CustomGradientButon alloc] 
      initWithFrame:CGRectMake(
      (self.view.bounds.size.width - 250)/2, 15.0, 250.0, 38.0)];
 
    [changeConditionsButton setButtonTitleLabel:@"Изменить условия поиска"];
    [changeConditionsButton addTarget:self 
      action:@selector(changeConditionsButtonClicked) 
      forControlEvents:UIControlEventTouchUpInside];
 
    [customView addSubview:changeConditionsButton];
 
    return customView;
 
}
 
-(void) changeConditionsButtonClicked {
 
    if (!fromFilter) {
       [self performSegueWithIdentifier:@"ChangeConditions" sender:self]; 
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
 
}

воскресенье, 11 августа 2013 г.

Passing Cyrillic characters as a URL parameter


NSString *str = textField.text; 
 
NSString *serverAddress = SERVER_ADDRESS;
 
NSString *restMethodAddress = @"/rest/someResource/someMethod";
 
NSString *encodeString = 
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
NSString *param = [NSString stringWithFormat:@"?charSequence=%@", encodeString];
 
NSMutableString *fullRequestAddress = [NSMutableString stringWithString:serverAddress];
[fullRequestAddress appendString:restMethodAddress];
[fullRequestAddress appendString:likeCitiesParam];
 
NSURL *url =[NSURL URLWithString:fullRequestAddress];
 
NSMutableURLRequest *theRequest = [NSMutableURLRequest 
requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
 
[theRequest setHTTPMethod:@"GET"];
 
NSURLConnection connection = 
[[NSURLConnection alloc] initWithRequest:theRequest delegate:self ];