Modifying Table Headers on Mac - objective-c

I've been able to find tutorials on modifying the table headers on iOS using UITableView - but havent been able to find any info for mac development. Does anyone know of any good resources / steps to modify the appearance of tables?
Zach

To change how the table headers appear you need to subclass NSTableHeaderCell, perform your own custom drawing in one of its drawing methods, then replace the header cells of each column with an instance of your subclass.
You may also find that you need to subclass NSTableHeaderView to draw the any space where no header cells are visible, and to replace the cornerView of the table view.
This should get you started:
for (NSTableColumn *column in [tableView tableColumns]) {
[column setHeaderCell:
[[[MyHeaderCell alloc]
initTextCell:[[column headerCell] stringValue]]
autorelease]];
}
And here’s a starting point for a subclass of NSTableHeaderCell:
#interface MyHeaderCell : NSTableHeaderCell
{
}
- (void)drawWithFrame:(CGRect)cellFrame
highlighted:(BOOL)isHighlighted
inView:(NSView *)view;
#end
#implementation MyHeaderCell
- (void)drawWithFrame:(CGRect)cellFrame
highlighted:(BOOL)isHighlighted
inView:(NSView *)view
{
CGRect fillRect, borderRect;
CGRectDivide(cellFrame, &borderRect, &fillRect, 1.0, CGRectMaxYEdge);
NSGradient *gradient = [[NSGradient alloc]
initWithStartingColor:[NSColor whiteColor]
endingColor:[NSColor colorWithDeviceWhite:0.9 alpha:1.0]];
[gradient drawInRect:fillRect angle:90.0];
[gradient release];
if (isHighlighted) {
[[NSColor colorWithDeviceWhite:0.0 alpha:0.1] set];
NSRectFillUsingOperation(fillRect, NSCompositeSourceOver);
}
[[NSColor colorWithDeviceWhite:0.8 alpha:1.0] set];
NSRectFill(borderRect);
[self drawInteriorWithFrame:CGRectInset(fillRect, 0.0, 1.0) inView:view];
}
- (void)drawWithFrame:(CGRect)cellFrame inView:(NSView *)view
{
[self drawWithFrame:cellFrame highlighted:NO inView:view];
}
- (void)highlight:(BOOL)isHighlighted
withFrame:(NSRect)cellFrame
inView:(NSView *)view
{
[self drawWithFrame:cellFrame highlighted:isHighlighted inView:view];
}
#end

Code to change column header in tableView:
NSString *title = #"Your Title";
NSTableColumn *yourColumn = self.tableView.tableColumns.lastObject;
[yourColumn.headerCell setStringValue:title];

Related

Why my NSBezierPath is not showing?

So i recieve a notification with the data i need to draw my path. This code is from my main app controller:
-(void) handleAdd:(NSNotification *)aNotification{
NSLog(#"x1:%f y1:%f x2:%f y2:%f ",[panelController x1],[panelController y1],[panelController x2],[panelController y2]);
myPath = [[NSBezierPath alloc]init];
[myPath setLineWidth:[panelController grosor]];
[myPath moveToPoint:NSMakePoint([panelController x1],[panelController y1])];
[myPath lineToPoint:NSMakePoint([panelController x2],[panelController y2])];
[[panelController trazado] setStroke];
[myPath stroke];
}
The NSLog is showing me the right data. I have a view created and in that white rectangle is where i want to draw.
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
NSRect bounds= [self bounds];
[[NSColor whiteColor] set];
[NSBezierPath fillRect:bounds];
}
If i draw in that class the stroke is showing, but how could i draw on that view from the controller? Or should i just receive the notification in the view and draw from that class?
You can't (easily) draw from the controller into the view.
Think of your views drawRect method as a complete set of instructions of what to draw at every refresh.
So right now all you are saying is "fill me with white"
You need to handle all the relevant drawing within the views drawRect: method.
Adjust your controller method to this.
-(void) handleAdd:(NSNotification *)aNotification{
[myViewInstance setNeedsDisplay:YES]; //also myViewInstance.needsDisplay = YES
}
And assuming the view has a reference to the panel controller…
#interface MyView: UIView
//weak as you don't want a reference cycle
#property (weak) MyPanelController *panelController;
#end
#implementation MyView
- (void)drawRect:(NSRect)dirtyRect
{
NSRect bounds= [self bounds];
[[NSColor whiteColor] set];
[NSBezierPath fillRect:bounds];
NSBezierPath *myPath = [[NSBezierPath alloc]init];
[myPath setLineWidth:[self.panelController grosor]];
[myPath moveToPoint:NSMakePoint([self.panelController x1],[self.panelController y1])];
[myPath lineToPoint:NSMakePoint([self.panelController x2],[self.panelController y2])];
[[self.panelController trazado] setStroke];
[myPath stroke];
}
#end
If you want explore your first technique you want to look at at NSView and the lockFocus/unlockFocus methods. The documentation explains why you probably don't want to do this.

Objective C, rounded corner custom window?

I have a subclass of NSWindow to customize one of my windows for my app.
I have everything set, but I am not sure how to make the corners round.
Currently, my window is a transparent rectangular window with some buttons, labels, and a textfield in it.
The class includes:
#import "TransparentRoundRectWindow.h"
#implementation TransparentRoundRectWindow
-(id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
if (self) {
[self setAlphaValue:0.75];
[self setOpaque:YES];
[self setHasShadow:YES];
[self setBackgroundColor:[NSColor clearColor]];
}
return self;
}
-(BOOL)canBecomeKeyWindow
{
return YES;
}
I just need to make the corners round now. I tried searching for similar situations and saw some of them explaining to override the drawRect method but I couldn't get them to work.
How could I do this?
(I'm using Mac OS X Lion)
Thanks in advance.
You need to set to Your window Opaque to NO. And subclass Your window's view.
Window subclass:
-(id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
if (self) {
[self setOpaque:NO];
[self setHasShadow:YES];
[self setBackgroundColor:[NSColor clearColor]];
}
return self;
}
-(BOOL)canBecomeKeyWindow
{
return YES;
}
Window's view subclass:
- (void)drawRect:(NSRect)rect
{
NSBezierPath * path;
path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:8 yRadius:8];
[[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.75] set];
[path fill];
}
Result:
More explanation how to do this:
Create new NSView class and paste "Window's view subclass" code which I wrote in it. Then go to Your window's view.
Here is window's view click on it:
Go to the Identity inspector and set class to your created class:

How can I custom UITableViewCell like Twitter?

I found that the iPad twitter.app UITableViewCell's border have two pixel line, it looks beautiful and professional,how can I do that? Thank you!
Because UITableViewCell inherits from UIView, a cell has a content view. You can add your own subviews (the labels and textfields) to that contentView and lay them out programmatically or using the Interface Builder.
There are a lot of online tutorials on how to accomplish that. Just search with google for "uitableviewcell interface builder tutorial".
Check out this pretty good tutorial Custom UITableViewCell Using Interface Builder.
Finally,I customed UITableViewCell use code,and I think it looks well. : )
MenuViewController.m file:
- (id)initWithFrame:(CGRect)frame {
if (self = [super init]) {
[self.view setFrame:frame];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
[_tableView setDelegate:self];
[_tableView setDataSource:self];
[_tableView setBackgroundColor:[UIColor clearColor]];
[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
[_tableView setTableFooterView:footerView];
[footerView release];
[self.view addSubview:_tableView];
}
return self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
DoubleSeparatorCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[DoubleSeparatorCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
NSString *text;
UIColor *upperLineColor,*lowerLineColor,*viewColor;
upperLineColor = RGBA(255, 255, 255, 30);
lowerLineColor = RGBA(0, 0, 0, 50);
viewColor = RGBA(0,0,0,5);
if ([indexPath row] == 0) {
text = NSLocalizedString(#"...", nil);
} else if ([indexPath row] == 1) {
text = NSLocalizedString(#"...", nil);
} else if ([indexPath row] == 2) {
text = NSLocalizedString(#"...", nil);
} else {
text = NSLocalizedString(#"...", nil);
}
[cell.textLabel setText:text];
[cell.textLabel setTextColor:RGBA(170, 170, 170, 100)];
[cell.textLabel setShadowColor:[UIColor blackColor]];
[cell.textLabel setShadowOffset:CGSizeMake(1, 1)];
[cell.upperLine setBackgroundColor:upperLineColor];
[cell.lowerLine setBackgroundColor:lowerLineColor];
[cell.contentView setBackgroundColor:viewColor];
return cell;
}
DoubleSeparatorCell.h
#interface DoubleSeparatorCell : UITableViewCell {
UIView *upperLine;
UIView *lowerLine;
}
#property (nonatomic ,retain) UIView *upperLine;
#property (nonatomic ,retain) UIView *lowerLine;
#end
DoubleSeparatorCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.upperLine = [[UIView alloc] init];
self.lowerLine = [[UIView alloc] init];
[self.contentView addSubview:self.upperLine];
[self.contentView addSubview:self.lowerLine];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
[self.upperLine setFrame:CGRectMake(0, 0, self.contentView.frame.size.width, 1)];
[self.lowerLine setFrame:CGRectMake(0, self.contentView.frame.size.height - 1, self.frame.size.width, 1)];
}
Srikar has already showed you the right path. By the way i just want to add the following:
You can cutomize your cell programmatically which can be done by inheriting the native class UITableViewCell.
Then by, create the instance of table view cell class and add it to the UITableView.
Now the cell is yours.
Happy Coding,
Arun
I'd point out that those cells you screenshot appear to have a light gray top border of 1 point and a dark gray bottom border of 1 point (or maybe they are pixels - sorry my eyes aren't that good :-) ).
So it may be kind of a hack (go on, savage me people), but you could:
Create a UILabel topBorder with frame CGRect(0,0,cell.contentView.frame.size,width,1)
Create a UILabel bottomBorder with frame CGRect (0,cell.contentView.frame.size.height - 1,cell.contentView.frame.size.width,1)
Set color of topBorder to UIColor lightGrayColor (or tweak for exact colors)
Set color of bottomBorder to UIColor darkGrayColor (ditto)
Add both subViews to cell.contentView
Note that you do not have to subclass UITableCellView - simply add these steps to your tableView:cellForRowAtIndexPath: method and they will appear.
Enjoy,
Damien
Override drawRect method and draw lines as you need.
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, [topColor CGColor]);
// border top
CGContextMoveToPoint(context, bounds.origin.x, bounds.origin.y);
CGContextAddLineToPoint(context, bounds.origin.x+bounds.size.width, bounds.origin.y);
CGContextStrokePath(context);
// border bottom
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, [lowerColor CGColor]);
CGContextMoveToPoint(context, bounds.origin.x, bounds.origin.y+1);
CGContextAddLineToPoint(context, bounds.origin.x+bounds.size.width, bounds.origin.y+1);
CGContextStrokePath(context);
}

NSScrollview with NSGradient

I have a nsscroll view in my application and i made a subclass of nsscrollview to add a nsgradient but it doesn't work this is my code in my implementation file:
#import "scrollview.h"
#implementation scrollview
#synthesize startingColor;
#synthesize endingColor;
#synthesize angle;
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
[self setStartingColor:[NSColor colorWithCalibratedRed:0.941 green:0.941 blue:0.941 alpha:1]];
[self setEndingColor:[NSColor colorWithCalibratedRed:0.6588 green:0.6588 blue:0.6588 alpha:1]];
[self setAngle:90];
}
return self;
}
- (void)drawRect:(NSRect)rect {
NSBezierPath* roundRectPath = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:10 yRadius:10];
[roundRectPath addClip];
if (endingColor == nil || [startingColor isEqual:endingColor]) {
// Fill view with a standard background color
[startingColor set];
NSRectFill(rect);
}
else {
// Fill view with a top-down gradient
// from startingColor to endingColor
NSGradient* aGradient = [[NSGradient alloc]
initWithStartingColor:startingColor
endingColor:endingColor];
[aGradient drawInRect:[self bounds] angle:angle];
}
}
The first step is to create a custom NSView subclass that draws a gradient:
GradientBackgroundView.h:
#interface GradientBackgroundView : NSView
{}
#end
GradientBackgroundView.m:
#import "GradientBackgroundView.h"
#implementation GradientBackgroundView
- (void) drawRect:(NSRect)dirtyRect
{
NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:[NSColor redColor] endingColor:[NSColor greenColor]] autorelease];
[gradient drawInRect:[self bounds] angle:90];
}
#end
The next step is to make the scroll view's document view an instance of this class (instead of plain NSView).
In IB, double-click your scroll view, and in the Identity pane set the Class to GradientBackgroundView.
From this point on, things are handled pretty much in the standard way. You can add subviews to the document view, resize it, etc. Here's a screenshot:

Objective C - Help with changing background color when UIButton is pressed

I am new to programing and any help is appreciated. I am trying to change the background color of a button once it has been pressed. I have tried setBackgroundColor without success. I am not sure that it is compatible with UIButton. Is there any way to programatically accomplish such a task? All thoughts and suggestions are appreciated.
I woudl suggest creating a simple image that contains the background color you want and setting that via the existing methods in the UIButton. (check Wrights Answer for the doc link).
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString* fileLocation = [[NSBundle mainBundle] pathForResource:#"buttonBG" ofType:#"png"];
UIImage* bgImage = [UIImage imageWithContentsOfFile:fileLocation];
if (bgImage != nil) { // check if the image was actually set
[button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
} else {
NSLog(#"Error trying to read the background image");
}
That should do the trick. There might be an even better way to create the necessary image on the fly, but that's stuff I'm not firm in.
[edit: a bit more verbose code ]
Assuming you have an unadorned custom button with a title of "On" for the normal state:
- (IBAction) toggleButtonState {
if ([toggleButton titleForState:UIControlStateNormal] == #"On") {
[toggleButton setTitle: #"Off" forState:UIControlStateNormal];
[toggleButton setBackgroundColor:[UIColor redColor]];
}
else {
[toggleButton setTitle: #"On" forState:UIControlStateNormal];
[toggleButton setBackgroundColor:[UIColor greenColor]];
}
}
All the other buttons have an image placed in front of the view, so at most you'll see the corners change if the image doesn't completely fill the space.
I'd also suggest using an image, but for learning purposes, this will work.
Ive just been having the same issue and ended up using a UIButton subclass to tackle the issue. I used gradients simply because it looked a bit better if you have no need for them you can simply remove them. I have explained the process I used and included the full code at the bottom of the post.
Firstly add properties for the layers.I created two layers one for the base gradient and one for a gloss to add a little bit of style.
#interface gradientButton()
#property (nonatomic, strong) CAGradientLayer* gradientLayer;
#property (nonatomic, strong) CAGradientLayer* glossyLayer;
#end
Then either in -(void)awakeFromNib or in -(id)initWithFrame:(CGRect)frame
,depending on if you will load from storyboard or code respectively, configure the gradients and add the layers, round your corners off and customize the font highlight color.
-(void)awakeFromNib
{
_gradientLayer = [[CAGradientLayer alloc] init];
_gradientLayer.bounds = self.bounds;
_gradientLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
[self.layer insertSublayer:_gradientLayer atIndex:0];
self.layer.cornerRadius = 5.0f;
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
_glossyLayer = [[CAGradientLayer alloc] init];
_glossyLayer.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height/2);
_glossyLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/4);
[self.layer addSublayer:_glossyLayer];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
}
Next, override - (void)drawRect:(CGRect)rect to apply your layers and define your colors.
#define GRADIENT_TOP [UIColor colorWithRed:38.0/255.0 green:78.0/255.0 blue:54.0/255.0 alpha:1]
#define GRADIENT_BOTTOM [UIColor colorWithRed:44.0/255.0 green:71.0/255.0 blue:56.0/255.0 alpha:1]
#define GLOSS_TOP [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.95f]
#define GLOSS_BOTTOM [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.35f]
#define GRADIENT_SELECTED_TOP [UIColor colorWithRed:138.0/255.0 green:178.0/255.0 blue:154.0/255.0 alpha:1]
#define GRADIENT_SELECTED_BOTTOM [UIColor colorWithRed:114.0/255.0 green:171.0/255.0 blue:156.0/255.0 alpha:1]
- (void)drawRect:(CGRect)rect
{
[_gradientLayer setColors:#[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
[_glossyLayer setColors:#[(id)[GLOSS_TOP CGColor], (id)[GLOSS_BOTTOM CGColor]]];
[super drawRect:rect];
}
Finally, and the bit we've all been waiting for, override -(void)setHighlighted:(BOOL)highlighted{
so we can apply the highlight effect were looking for.
-(void)setHighlighted:(BOOL)highlighted{
[super setHighlighted:highlighted];
if(highlighted)
[_gradientLayer setColors:#[(id)[GRADIENT_SELECTED_TOP CGColor],(id)[GRADIENT_SELECTED_BOTTOM CGColor]]];
else
[_gradientLayer setColors:#[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
}
There we have it, now just drag out a UIButton modify the class and your all good. Heres the full Implementation so you can copy it straight out. http://pastebin.com/nUVeujyp
Check out the UIButton Class Reference.
Regular UIButtons do not have the backgroundColor option.
My suggestion would to use the UISegmentedControl, which has the tinColor option.
I have created a subclass which get background color and creates an UIImage for each state.
For me it's more useful a subclass instead a category, so that's up to you.
#implementation ROCRoundColorButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIColor *darkColor;
darkColor = [self darkColorFromBackgroundColor];
[self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
[self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
UIColor *darkColor;
darkColor = [self darkColorFromBackgroundColor];
[self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
[self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#pragma mark -
#pragma mark Private methods
- (UIColor *)darkColorFromBackgroundColor
{
const float* components = CGColorGetComponents( self.backgroundColor.CGColor );
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = components[3];
if (red > 0) {
red -= 0.1;
}
if (green > 0) {
green -= 0.1;
}
if (blue > 0) {
blue -= 0.1;
}
UIColor *darkColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
return darkColor;
}
- (UIImage *)imageWithColor:(UIColor *)color withSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
//CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:5];
[roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];
[color setFill];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
In fact, you can use it in the storyboard, changing the class and setting de background color in the view.