Monday, 1 July 2013

UIButton Or UILabel with underlined text. iOS 6.


For iOS 6 -----------

    NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"ADD ANOTHER CONTACT"];

    [commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];

// Or for adding Colored text use----------
    UIColor* textColor = [UIColor blueColor];
    [commentString setAttributes:@{NSForegroundColorAttributeName:textColor,NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[commentString length])];
// Or for adding Colored text use----------

    [_addContactButton setAttributedTitle:commentString forState:UIControlStateNormal];




For Below iOS 6 -----------
Modify drawRect: function in subclass of UIButton.

UnderlinedButton.h
@interface UnderlinedButton : UIButton {

}


+ (UnderlinedButton*) underlinedButton;
@end 
UnderlinedButton.m
@implementation UnderlinedButton

+ (UnderlinedButton*) underlinedButton {
    UnderlinedButton* button = [[UnderlinedButton alloc] init];
    return button;
}

- (void) drawRect:(CGRect)rect {
    CGRect textRect = self.titleLabel.frame;

    // need to put the line at top of descenders (negative value)
    CGFloat descender = self.titleLabel.font.descender;

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    // set to same colour as text
    CGContextSetStrokeColorWithColor(contextRef, self.titleLabel.textColor.CGColor);

    CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender);

    CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender);

    CGContextClosePath(contextRef);

    CGContextDrawPath(contextRef, kCGPathStroke);
}


@end

Friday, 28 June 2013

Show picker view (UIDatePicker) on tapping text field.


We can use inputView and inputAccessoryView of UITextField. Declare in .h file, and @synthesize in .m file.
@property (nonatomic, retain) IBOutlet UIToolbar    *_accessoryView;
@property (nonatomic, retain) IBOutlet UIDatePicker *_datePickerView;
Connect them to File's Owner in .xib file, make sure that its out of the self.view.
- (void)viewDidLoad
    {   
        _dateOfBirthTextField.inputView = self._datePickerView;
        _dateOfBirthTextField.inputAccessoryView = self._toolbar;
    }
Also write function to fetch date from the picker
#pragma mark- UITextField with UIDatePicker-

- (IBAction)dateChanged:(id)sender {
    UIDatePicker *picker = (UIDatePicker *)sender;
    _dateOfBirthTextField.text = [NSString stringWithFormat:@"%@", picker.date];
}

- (IBAction)doneEditing:(id)sender {
    [_dateOfBirthTextField resignFirstResponder];
}
Add dateChanged: IBAction on valueChanged: action of _datePicker. and doneEditing: IBAction on toolbar barbutton action.

Thursday, 27 June 2013

Fetching the images and title of songs and albums ( MPMediaItem ) in the table view. Music Player iOS.


If you want to using default Music player in your app, you can fetch the images of the related song or album using various properties from "MPMediaItemProperty" like MPMediaItemPropertyAlbumTitle, MPMediaItemPropertyArtist, MPMediaItemPropertyTitle, MPMediaItemArtwork.



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *CellIdentifier = @"Cell";
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d",indexPath.section,indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
    }

    MPMediaItem* mediaItem = [_arrPlaylistOfMediaItems objectAtIndex:indexPath.row] ; 
    //_arrPlaylistOfMediaItems is the array of MPMediaItems 
    NSString* mediaTitle = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
    NSString* title = [[NSString alloc]initWithFormat:@"%@",(mediaTitle.length>0 ? mediaTitle : @"Unknown")];
    NSString* artist = [mediaItem valueForProperty:MPMediaItemPropertyArtist];
    NSString* albumTitle = [mediaItem valueForProperty:MPMediaItemPropertyAlbumTitle];
    NSString* subTitle = [[NSString alloc]initWithFormat:@"%@ - %@",(artist.length>0 ? artist : @"Unknown"),(albumTitle.length>0 ? albumTitle : @"Unknown")];

    cell.textLabel.text = title;
    cell.detailTextLabel.text = subTitle;
    cell.imageView.image = _defaultImg;//[UIImage imageNamed: @"iconThumb"];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        MPMediaItemArtwork* artwork = [mediaItem valueForProperty:MPMediaItemPropertyArtwork];
        if ( !artwork || artwork.bounds.size.width == 0 ) {
            // try album artwork
            NSNumber* albumID = [mediaItem valueForProperty:MPMediaItemPropertyAlbumPersistentID];
            MPMediaQuery*   mediaQuery = [MPMediaQuery albumsQuery];
            MPMediaPropertyPredicate* predicate = [MPMediaPropertyPredicate predicateWithValue:albumID forProperty:MPMediaItemPropertyAlbumPersistentID];
            [mediaQuery addFilterPredicate:predicate];
            NSArray* arrMediaItems = [mediaQuery items];
            if ( [arrMediaItems count] > 0 ) {
                artwork = [[arrMediaItems objectAtIndex:0] valueForProperty:MPMediaItemPropertyArtwork];
                if ( artwork ) {
                    int nBreak = 0;
                    nBreak++;
                }
            }
        }
       dispatch_sync(dispatch_get_main_queue(), ^{
            if ( artwork && artwork.bounds.size.width > 0 ) {
                      cell.imageView.image = [self scale: [artwork imageWithSize:CGSizeMake (50, 50)] toSize:CGSizeMake(55, 55)] ;
                cell.imageView.image =[self scale:[artwork imageWithSize:CGSizeMake(50,50)]toSize:CGSizeMake(45,45)];
            }
            else {
                 NSLog(@"Bad artwork: %@ - %@ - %f-%f", strTitle, strsubTitle, artwork.bounds.size.width, artwork.bounds.size.height);
                
                cell.imageView.image = _defaultImg;
            }
       });
    });
   return cell;
}

GCD - Fetching data for UIImage on background thread, and updating UI on main thread.



// Perform the asynchronous task on the background thread-

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

       // Perform the asynchronous task in this block like loading data from server

       NSString *ImageURL = 
            @"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqAPlN0cfFStsejGreGWs1xiRVBPbEt6e0r86g83drW6RVlBHLVnY75EqG964qZlPv6ZGNwMS-t6Ci8cgdpgwWUsaTJ6DVKDMkKxDc9Ovy4bdKkpmkZrJxCRjPjLCNpwnpPqNZHPwLync/s220-h/smart-software-developer.jpg";

       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];


       // Perform the task on the main thread using the main queue-
        dispatch_sync(dispatch_get_main_queue(), ^{

            // Perform the UI update in this block, like showing image.

            _imageObj.image = [UIImage imageWithData:imageData];

        });

 });

Wednesday, 26 June 2013

Single UILabel with different color text and fonts possible?


Yes, Its possible in to have different colored text and fonts in single UILabel, from iOS6 onwards using "NSMutableAttributedString".

-(void)AttributedTextInUILabelWithGreenText:(NSString *)greenText withYellowText:(NSString *) yellowText withBlueBoldText:(NSString *)blueBoldText
{
    NSString *text = [NSString stringWithFormat:@"Here are %@, %@ and %@",
                      greenText,
                      yellowText,
                      blueBoldText];

    //Check If attributed text is unsupported (below iOS6+)
    if (![self.label respondsToSelector:@selector(setAttributedText:)]) {   
     self.label.text = text;
    }
    // If attributed text is available
    else {
        // Define general attributes like color and fonts for the entire text
        NSDictionary *attribs = @{
                                  NSForegroundColorAttributeName: self.label.textColor,
                                  NSFontAttributeName: self.label.font
                                  };
        NSMutableAttributedString *attributedText =
        [[NSMutableAttributedString alloc] initWithString:text
                                               attributes:attribs];

        // green text attributes
        UIColor *greenColor = [UIColor greenColor];
        NSRange greenTextRange = [text rangeOfString:redText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:greenColor}
                                range:greenTextRange];

        // yellow text attributes
        UIColor *yellowColor = [UIColor yellowColor];
        NSRange yellowTextRange = [text rangeOfString:greenText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:yellowColor}
                                range:yellowTextRange];

        // blue and bold text attributes
        UIColor *blueColor = [UIColor blueColor];
        UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
        NSRange blueBoldTextRange = [text rangeOfString:blueBoldText];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:blueColor,
                  NSFontAttributeName:boldFont}
                                range:blueBoldTextRange];
        self.label.attributedText = attributedText;
        
}