Question

I am able to draw my NSStrings, but I have not been able to adjust the size when I draw them. My drawRect: method is:

- (void)drawRect:(CGRect)rect
{

NSArray *objectArray = [NSArray arrayWithObjects:[UIFont systemFontOfSize:80.0f], nil];
NSArray *keyArray = [NSArray arrayWithObjects:@"NSFontAttributeName", nil];
NSMutableDictionary *textAttributes = [NSMutableDictionary dictionaryWithObjects:objectArray forKeys:keyArray];
NSString *myTestString = @"Test String";
[textAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
[myTestString drawAtPoint:CGPointMake(20, 30) withAttributes:textAttributes];
[myTestString drawInRect:CGRectMake(50, 50, 500, 500) withAttributes:textAttributes];

NSLog(@"wrote %@ with %@", myTestString, textAttributes);
}

The textAttributes look good, and the font information is returned as:

 NSFontAttributeName = "<UICTFont: 0x14eeff40> font-family: \".HelveticaNeueInterface-M3\"; font-weight: normal; font-style: normal; font-size: 80.00pt"

I can change the color correctly with the attributes array, why does this result in text that is the default 10pt Size?

Was it helpful?

Solution

NSAttributedString is what you want. The UICatalog sample code has an example of NSAttributedString usage:

#pragma mark - UIPickerViewDataSource

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSMutableAttributedString *attrTitle = nil;

    // note: for the custom picker we use custom views instead of titles
    if (pickerView == self.myPickerView)
    {
        if (row == 0)
        {
            NSString *title;
            if (component == 0)
                title = [self.pickerViewArray objectAtIndex:row];
            else
                title = [[NSNumber numberWithInt:row] stringValue];

            // apply red text for normal state
            attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
            [attrTitle addAttribute:NSForegroundColorAttributeName
                          value:[UIColor redColor]
                          range:NSMakeRange(0, [attrTitle length])];
        }
    }

    return attrTitle;
}

The Stanford U MOOC course on iOS (run by Paul Hegarty and available on iTunes) gives an overview of NSAttributedString use in lecture 4. Lecture 5 also features an NSAttributedString code demo that you can follow. Finally, github user m2mtech has published repositories of all code exercises and assignments for the course, you can download the relevant project files here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top