Subclass UITableView to change font colour of the section index? - iphone

I have a dark background with a UITableView on top of it. By default the section index is semi-transparent with a dark text colour. I'd like to change the text colour for the section index to the same colour as I have made the UITableViewCell title label. I have read around a bit and it seems you have to subclass the UITableView? How do I do this?

Since iOS 6 you have the possibility to do it like:
searchTable.sectionIndexColor = [UIColor blackColor];

To solve this I used the following in viewDidAppear:
for (UIView *subView in [self.view subviews])
{
if ([[[subView class] description] isEqualToString:#"UITableViewIndex"])
{
[subView performSelector:#selector(setIndexColor:) withObject:[UIColor whiteColor]];
}
}
Since it's not documented, it has to be through a selector.

As of iOS 6.0 there are two methods that allow you to change the color of the section indexes and the background shown when you drag the scrubber.
if ([tableView respondsToSelector:#selector(setSectionIndexColor:)]) {
tableView.sectionIndexColor = ... // some color
tableView.sectionIndexTrackingBackgroundColor = ... // some other color
}
Of course this will only execute if the device has 6.0+. With any older iOS, nothing will change.

Related

Making text color of UILabel same as UITableView header's text color

For one of my application, I have added UILabel to the UITableView header section.
But I want the text color of UILabel should also be the same as what it is displayed for table's header section (some gray shades).
How can I do this?
Thanks in advance.
try to traverse UITableView subviews hierarchy looking for UILabels and then logging its attributes:
-(void)traverseView:(UIView *)view{
for(UIView *subview in view.subviews){
if ([subview isKindOfClass:[UILabel class]]){
NSLog(#"font:%#",[(UILabel *)subview font]);
NSLog(#"color:%#",[(UILabel *)subview textColor]);
NSLog(#"and so on:%#",[(UILabel *)subview anotherProperty]);
}else{
[self traverseView:subview];
}
}
}
-(void)lookForIt:(UITableView *)tableView{
[self traverseView:tableView];
}
I got a workaround.
From one of stack-overflow question, I got a RGB value (RGB: 76, 86, 108 with font style BOLD and size is 16) for the text color used by UITableView's Header section. I am currently using the same for setting the text color of UILabel.
I would appreciate if one can tell me the way to know the textColor of UITableView programmatically so that the hard code RGB values will not be used.
Thank you for your support.

background color in above (bounce part) of UIWebView

I think this shouldn't be a big problem, but I can't find the solution on my own. As always :p I have an UIWebView that has background color set to clearColor but when I try to scroll down too much I get the "bouncing area" above loaded HTML in dark gray color. I would like to change this to transparent/white. Is there any way of changing this?
Digression: I read that classes inheriting UIScrollView can have property bounce = NO and then they won't show the bouncing area at all. Even if UIWebView was inheriting that class I wouldn't like to stop it from bouncing, just "bounce it in white" so to speak...
Thanks a lot,
Luka
Take a look at the following answer
Remove gradient background from UIWebView?
Set the webview's background colour and set opaque to NO:
[self.webView setBackgroundColor:[UIColor whiteColor]];
[self.webView setOpaque:NO];
Or try setting clear color as background:
[self.webView setBackgroundColor:[UIColor clearColor]];
[self.webView setOpaque:NO];
#Ladislav: thanks for pointing me to the right subject :)
Now, the following post Remove gradient background from UIWebView? is exactly what I needed, so I am sorry I opened the new thread. I searched the forum but since there is no name for this gradient, bounce background or background I couldn't find it earlier.
The summary would be:
1.Setting the backgroundColor of web view to clearColor !in code! cause in interface builder is not producing the wanted result.
myWebView.backgroundColor = [UIColor clearColor];
this line will only make the "overscroll" background look lighter, but to remove it totally (make it transparent/white) we need to hide all imageViews found in subViews of our myWebView:
for (UIView* subView in [self.myWebView subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
Thanks everyone, I wish you a great weekend

How can I set the background of UITableView (the tableview style is "Grouped") to use an image?

How can I set the background of UITableView (the tableview style is "Grouped") to use an image?
In newer versions of the SDK, you'll need to set tableView.backgroundView if you want it to be transparent, try something like this:
tableView.backgroundColor = [UIColor clearColor];
tableView.opaque = NO;
tableView.backgroundView = nil;
We need to do something about that plain background. We're going to use a PNG image and display it behind the UITableView.
Prepare a PNG image. It should be either 320x460 (if you have the status bar visible in your app) or 320x480 (if you hide it).
Drag it into XCode into the Resources folder and add to your project
Load the NIB file containing your UITableView into Interface Builder
Open the library (Tools> Library), switch to the Media tab, and drag the image to the View, create a new UIImageView.
Use the inspector to move and resize the image so it's at X=0, Y=0, Width=320, Height=480
Put the UIImageView behind the UITableView (Layout > Send to Back)
Save, Build and Go!
Disappointingly, you won't be able to see your background. The UITableView's background is blocking us from seeing the UIImageView. There are three changes you need to make:
In the Attributes Inspector, make sure the UITableView's "opaque" checkbox is unchecked!
Set the UITableView's background color to transparent:
tableView.backgroundColor = [UIColor clearColor];
I hope this helps and solves your problem. It has worked for me and I have yet to find a more elegant way to display a background image for a UITableView.
The advantage of my solution, in comparison with setting a background image directly on the UITableView, is that you can indent the table's content. I often wanted to do this to just show two or three table cells at the bottom of the screen.
[tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"whatever.png"]]];
tableView.backgroundView = nil;
is enough. No need to set background color as Clear Color.
One way would be to make the table view transparent (set the view's background to 0% opacity) and place a UIImageView behind the UITableView. Remember that transparent tables and table cells will not perform as well as opaque ones.
In UI Builder the Background color has an "Other" choice.
This brings up a color picker.
The color picker has an opacity setting.
If you set the Opacity of the COLOR to 0 it works, can't speak to performance.
What I've found is that you have to use a "plain" styled table with a transparent background and then recreate the look of the rounded-corner cells by setting each cell's backgroundView to a UIImageView with a image that simulates the rounded look. This means that the top, bottom, and middle cells need different background images.
However, this does not address what happens when the user taps the cell and it goes "highlighted" - it will look squared off then. You can get around this by setting the highlighted image for your faked tablecell background image. You will also want to create your own disclosure accessory view (ImageView) with a white highlighted version. Then you can create a cell like this one I'm using (below). After I alloc one of these cells I then set the backgroundView and accessoryView to my UIImageViews.
#import "ClearBackRoundedTableCell.h"
#implementation ClearBackRoundedTableCell
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
}
return self;
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
if( [[self.accessoryView class] isSubclassOfClass:[UIImageView class]] )
((UIImageView *)self.accessoryView).highlighted = highlighted;
if( [[self.backgroundView class] isSubclassOfClass:[UIImageView class]] )
((UIImageView *)self.backgroundView).highlighted = highlighted;
self.textLabel.highlighted = highlighted;
}
#end
One note if you go this route: the cells in a grouped table are typically 300 px wide (in portrait mode) but your plain table here would need to be 302 wide to allow for the grey line on each side of the table, which is normally outside of the "content" of the table cell.
After spending a while with color picker, I found out that you need to specify opaque background not for the table view cell xib, but for the Table View where the cells will be located, which is another xib. From what I have seen, table view cell background attributes have no visual effect.
try this one
UIView *backView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;
It worked for me in grouped tableview.
Make UITableview background as clear color.
Programmatically you can do it like this if your image is added into your resources:
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.opaque = NO;
UIImage *backroundImage = [UIImage imageNamed:#"my_backround"];
UIImageView *backroundImageView = [[UIImageView alloc] initWithImage:backroundImage];
Else you can do it in Interface Builder with this style :
You may need to configure the header files interface from UITableViewController to UIViewController and add <UITableViewDataSource,UITableViewDelegate> ,also don't forget to set the attributes of the tableview to not be opaque and reconnect the tableviews datasource and delegate outlets to the viewcontroller.

How can I set the background color of a cell in UITableView on iphone?

How can I set the background color of a cell in UITableView?
Thanks.
I know this is an old post, but I am sure some people are still looking for help. You can use this to set the background color of an individiual cell, which works at first:
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
[cell setBackgroundColor:[UIColor lightGrayColor]];
However, once you start scrolling, the iphone will reuse cells, which jumbles different background colors (if you are trying to alternate them). You need to invoke the tableView:willDisplayCell:forRowAtIndexPath. This way, the background color gets set before the reuse identfier is loaded. You can do it like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = ([indexPath row]%2)?[UIColor lightGrayColor]:[UIColor whiteColor];
}
The last line is just a condensed if/else statement. Good luck!
Update
Apparently the existing UITableViewCell framework makes it very difficult to change the background color of a cell and have it work well through all its state changes (editing mode, etc.).
A solution has been posted at this SO question, and it's being billed on several forums as "the only solution approved by Apple engineers." It involves subclassing UITableViewCell and adding a custom view for the subclassed cell's backgroundView property.
Original post - this solution doesn't work fully, but may still be useful in some situations
If you already have the UITableViewCell object, just alter its contentView's backgroundColor property.
If you need to create UITableViewCells with a custom background color, the process is a bit longer. First, you'll want to create a data source for your UITableView - this can be any object that implements the UITableViewDataSource protocol.
In that object, you need to implement the tableView:cellForRowAtIndexPath: method, which returns a UITableViewCell when given an NSIndexPath for the location of the cell within the table. When you create that cell, you'll want to change the backgroundColor property of its contentView.
Don't forget to set the dataSource property of the UITableView to your data source object.
For more info, you can read these API docs:
UITableViewDataSource - tableView:cellForRowAtIndexPath
UITableViewCell - contentView
UIView - backgroundColor
UITableView - dataSource
Note that registration as an Apple developer is required for all three of these links.
The backgroundView is all the way on the bottom. It's the one that shows the rounded corners and the edges. What you want is the contentView which is on top of the backgroundView. It covers the usually white area of the cell.
The version I wrote will work in iPhone 3.0 or higher and fallback to a white background otherwise.
In your viewDidLoad method of the UITableViewController we add the following:
self.view.backgroundColor=[UIColor clearColor];
// Also consider adding this line below:
//self.tableView.separatorColor=[UIColor clearColor];
When you are creating your cells (in my code this is my tableView:cellForRowAtIndexPath:) add the following code:
cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"code_bg.png"]];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 3.0)
{
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
}
This works perfectly for me:
NSEnumerator *enumerator = [cell.subviews objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject]) {
if( [anObject isKindOfClass: [ UIView class] ] )
((UIView*)anObject).backgroundColor = [UIColor lightGrayColor];
}
You may set the backgroundColor of the backgroundView. If the backgroundView does not exists, you can create one for it.
if (!tableView.backgroundView) {
tableView.backgroundView = [[UIView alloc] initWithFrame:tableView.bounds];
}
tableView.backgroundView.backgroundColor = [UIColor theMostFancyColorInTheUniverse];
If you want to set the background of a cell to an image then use this code:
// Assign our own background image for the cell
UIImage *background = [UIImage imageNamed:#"image.png"];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;

How do I change the color of the side Alphabet in an indexed UITableView?

I have a table view with an alphabetical index and am using the side alphabet to get through the list quickly. For those not familiar, that uses this:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
My problem is that my application has just been skinned black. And so now it's hard to see the alphabet letters on the side.
I can't figure out how to change the color of the alphabet. I'd like it to be 'white' if at all possible.
if your minimum iOS version is newer than 6.0, you can use sectionIndexColor property of UITableView.
The color to use for the table view’s index text.
#property(nonatomic, retain) UIColor *sectionIndexColor
Discussion:
Table views can display an index along the side of the view, making it
easier for users to navigate the contents of the table quickly. This
property specifies the color to use for text displayed in this region.
Update date 2014.1.13
I find an open source third party library:GDIIndexBar to help custom the index appearance.
From what I can tell unfortunately it is not possible to customize the color of the text displayed in the index, the closest I've been able to come is being able to modify the background color and the font of the index.
There is some code in the iPhone Developers cookbook by Erica Sadun which shows how to access the UITableViewIndex view (an undocumented class). You can find the reference to it on page 175 of the book if you have it. Which gives access to the background color and the font. You can see an unofficial document related to this class here.
WARNING This is undocumented use of an undocumented class so you need to be cautious about using it.
Here is a code snippet from the cookbook with minor modifications:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
for(UIView *view in [tv subviews])
{
if([[[view class] description] isEqualToString:#"UITableViewIndex"])
{
[view setBackgroundColor:[UIColor whiteColor]];
[view setFont:[UIFont systemFontOfSize:14]];
}
}
//rest of cellForRow handling...
}
This illustrates how you can access and the UITableViewIndex view and modify it in some aspects. It looks like the view doesn't have any subviews so it is likely doing some custom drawing with the array of index titles.
It's not perfect but hopefully it helps a little.
Paul
This can be easily changed in the interface builder for the UITableView - No need to use undocumented classes?
See screenshot below, as you can see the font colour and the background colour can be changed too. Job's a good'n!
For iOS7 or Higher:
self.tableView.sectionIndexColor = [UIColor whiteColor];
self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
I was having the same problem and just found out a way of doing this, though this is using undocumented classes and methods so think one extra time before trying to upload it to the App Store.
I should say that i've only tried this with iOS5 so I don't know if it will work for previous versions.
I borrowed and modified the Erica Saunders cookbook example so that it now changes the text color to red:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
for(UIView *view in [tv subviews])
{
if([[[view class] description] isEqualToString:#"UITableViewIndex"])
{
[view performSelector:#selector(setIndexColor:) withObject:[UIColor redColor]];
}
}
//rest of cellForRow handling...
}
We have successfully used the following code:
for(UIView *view in [tableView subviews]) {
if([view respondsToSelector:#selector(setIndexColor:)]) {
[view performSelector:#selector(setIndexColor:) withObject:[UIColor whiteColor]];
}
}
which works fine - it's very similar to Mooglas answer - but refrains from using the word "UITableViewIndex".
You can set the tint color for the tableView.
[[UITableView appearance] setTintColor:[UIColor purpleColor]];
Swift 5:
tableView.sectionIndexColor = .red
tableView.sectionIndexBackgroundColor = .clear
There is a way to change the color of the index Alphabet.
In your header file, declare your UITableView as a property:
#property (weak, nonatomic) IBOutlet UITableView *mainTable;
Then in your implementation file's viewDidAppear, use the following line:
//Change the color of the UITableView index color
_mainTable.sectionIndexColor = [UIColor blackColor];
Here's the best solution I've found to adjust the background colour of the index bar on the side. It works in iOS7 and probably iOS6.
Add this to your viewDidLoad
if ([_tableView respondsToSelector:#selector(setSectionIndexColor:)]) {
_tableView.sectionIndexBackgroundColor = [UIColor clearColor];
_tableView.sectionIndexTrackingBackgroundColor = [UIColor whiteColor];
}
The first one is the default colour, the second is the background colour when you are scrolling.
Make a mutable array to contain the alternate title label
In
-(NSArray * )sectionIndexTitlesForTableView:(UITableView * )tableView
return an array of #" " where the number of spaces between the quotes determines the width of the hi-lighted scroller.
Have "sectionIndexTitlesForTableView" call an update label function.
In that function remove all the labels in the array you created earlier from their superviews Then create and add however many labels are needed. Then add them to the table's superview.
These are the lines required to place the labels in the right place.
rect.origin.x = table.frame.origin.x+table.frame.size.width-rect.size.width-2;
rect.origin.y = 5+table.frame.origin.y+counter *(280-rect.size.height-([customIndexLabels count]-1))/([customIndexLabels count]-1);
if ([customIndexLabels lastObject]==thisLabel)
{
rect.origin.y-=10;
}
Hope that helps. It's not perfect I just don't care enough to fix it myself
The main problem is that the spacing of the last label is not uniform.
Swift edition for undocumented font change:
extension NSObject {
class func objectClassName() -> String {
let classLongName = reflect(self.self).summary;
let tokens = classLongName.componentsSeparatedByString(".")
if let typeName = tokens.last {
return typeName
}
return NSStringFromClass(self.dynamicType)
}
}
func changeSectionIndexFont(tableView: UITableView) -> Void {
let realSubviews = tableView.subviews as! [UIView]
for subview in realSubviews {
if subview.dynamicType.objectClassName() == "UITableViewIndex" {
subview.setValue(UIFont(name: "OpenSans", size: 10), forKey: "font")
}
}
}