One Quickie


Unique looking custom placeholder views (UIView->Hacks)
Every now and then I want a placeholder view that just draws itself. In this particular case, I wasn't sure where the contents of various view controllers were being set up, and whether it was re-using views or making them new each time. I added one of these to the view hierarchy. If I saw it, I know where it was created. Because the color is based on the view's address, each view will get a different color, making it easy to see if distinct views are being used or if one is being recycled.
@interface BlahView : UIView
@end

@implementation BlahView

- (void) drawRect: (CGRect) rect {
    CGRect bounds = self.bounds;

    UIColor *color = [UIColor colorWithRed: (((int)self >> 0) & 0xFF) / 255.0
                              green: (((int)self >> 8) & 0xFF) / 255.0
                              blue: (((int)self >> 16) & 0xFF) / 255.0
                              alpha: 1.0];

    [color set];
    UIRectFill(bounds);

    [[UIColor blackColor] set];
    UIRectFrame(bounds);
} // drawRect

@end // BlahView

...

       CGRect frame = CGRectMake(200, 5, 300, 30);
        BlahView *view = [[BlahView alloc] initWithFrame: frame];
        [viewController.view addSubview:view];
And here is the version for Cocoa-non-touch:
@interface BlahView : NSView
@end

@implementation BlahView

- (void) drawRect: (CGRect) rect {
    CGRect bounds = self.bounds;

    NSColor *color = [NSColor colorWithDeviceRed: (((int)self >> 0) & 0xFF) / 255.0
                              green: (((int)self >> 8) & 0xFF) / 255.0
                              blue: (((int)self >> 16) & 0xFF) / 255.0
                              alpha: 1.0];

    [color set];
    NSRectFill(bounds);

    [[NSColor blackColor] set];
    NSFrameRect (bounds);
} // drawRect

@end // BlahView
And for Swift/Cocoa-touch:
func prettyColor(instance: T) -> UIColor {
       var address = unsafeBitCast(instance, Int.self)
       let red =   CGFloat(address >> 0 & 0xFF) / 255.0
       let green = CGFloat(address >> 8 & 0xFF) / 255.0
       let blue =  CGFloat(address >> 16 & 0xFF) / 255.0

       let derivedColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
       return derivedColor
   }
(thanks to Step Christopher for the translation)



borkware home | products | miniblog | rants | quickies | cocoaheads
Advanced Mac OS X Programming book

webmonster@borkware.com