UITextView ruled line background but wrong line height - iphone

I have a UITextView where the user can create notes and save into a plist file.
I want to be able to show lines just like a normal notebook. The problem I have is
that the text won't align properly.
The image below explains the problem quite well.
This is the background I use to create the lines like the Notes.app
This is my code for creating the background for my UITextView:
textView.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:19.0];
textView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: #"Notes.png"]];
I know that the UIFont.lineHeight property is only available in > iOS 4.x.
So I wonder if there is another solution to my problem?

You should try and draw your lines programmatically rather than using an image. Here's some sample code of how you could accomplish that. You can subclass UITextView and override it's drawRect: method.
NoteView.h
#import <UIKit/UIKit.h>
#interface NoteView : UITextView <UITextViewDelegate> {
}
#end
NoteView.m
#import "NoteView.h"
#implementation NoteView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithRed:1.0f green:1.0f blue:0.6f alpha:1.0f];
self.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:19];
}
return self;
}
- (void)drawRect:(CGRect)rect {
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.2f].CGColor);
CGContextSetLineWidth(context, 1.0f);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading;
//Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading*x + 0.5f + baselineOffset);
}
//Close our Path and Stroke (draw) it
CGContextClosePath(context);
CGContextStrokePath(context);
}
#end
MyViewController.h
#import <UIKit/UIKit.h>
#import "NoteView.h"
#interface MyViewController : UIViewController <UITextViewDelegate> {
NoteView *note;
}
#property (nonatomic, retain) NoteView *note;
#end
MyViewController.m
#import "MyViewController.h"
#import "NoteView.h"
#define KEYBOARD_HEIGHT 216
#implementation MyViewController
#synthesize note;
- (void)loadView {
[super loadView];
self.note = [[[NoteView alloc] initWithFrame:self.view.bounds] autorelease];
[self.view addSubview:note];
note.delegate = self;
note.text = #"This is the first line.\nThis is the second line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\n";
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[note setNeedsDisplay];
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
CGRect frame = self.view.bounds;
frame.size.height -= KEYBOARD_HEIGHT;
note.frame = frame;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
note.frame = self.view.bounds;
}
- (void)dealloc {
[note release];
[super dealloc];
}
Take a look at Apple's documentation for Managing the Keyboard, specifically "Moving Content That Is Located Under the Keyboard". It explains how to listen for NSNotifcations and adjust your views properly.

I think the problem is with your image, the yellow space over the line is creating the problem.
You should edit the image.
And nice work.

Related

Draw line in UITextView

I want to draw line in my UITextView. After some research I found this:
UITextView ruled line background but wrong line height
I tried in my code, drawRect is called but no line is drawn.. Someone could help me out here ?
#import "FacebookViewController.h"
#import <QuartzCore/QuartzCore.h>
#interface MyViewController (){
UITextView *text;
}
#end
#implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Do any additionnal customisation
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
text.contentMode = UIViewContentModeRedraw;
//TextView init
text = [[UITextView alloc]initWithFrame:CGRectMake(0,44,320,380)];
[self.view addSubview:text];
text.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)drawRect:(CGRect)rect {
NSLog(#"TEST");
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 1.0f);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (text.contentSize.height + text.bounds.size.height) / text.font.leading;
//Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, text.bounds.origin.x, text.font.leading*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, text.bounds.size.width, text.font.leading*x + 0.5f + baselineOffset);
}
CGContextClosePath(context);
CGContextStrokePath(context);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[text setNeedsDisplay];
}
#end
Probably a silly mistake but I can't find it out
Thanks
As i looked to you code everything is ok with it. Maybe there is something with color? May be it is the same as background color or something like this.
May be you forgot to set content mode:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.contentMode = UIViewContentModeRedraw;
}
return self;
}
EDIT:
I think i know:
You forgot to set [myTextView setNeedsDisplay]; after showing it. Read here
EDIT:
First you create your view:
t = [[[MyTextView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)] autorelease];
[self.view addSubview:t];
t.delegate = self;
Make your viewcontroller implement UITextViewDelegate and after that
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[t setNeedsDisplay];
}
This should work
I have same problem ..
As i think you are not subclassing from UITextView
As UIViewController does not implement this method only UITextView did
So just subclass it .. you code will work
Is it possible that you're drawing successfully but getting obscured by a matching background color? I notice that the alpha on the color you've chosen is pretty small. If only to rule this out, change:
CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0.5f alpha:0.15f].CGColor);
to
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

textview cursor position changed after horizontal line

I want to change the cursor position in TextView...
// NoteView objective _c class its super class is TextView...
#import "NoteView.h"
#implementation NoteView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor =[UIColor whiteColor];
self.contentMode = UIViewContentModeRedraw;
self.font = [UIFont fontWithName:#"Helvetica Neue" size:14];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
// CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.2f].CGColor);
CGContextSetStrokeColorWithColor(context,[UIColor colorWithRed:0.29804f green:0.12157f blue:0.9f alpha:0.1].CGColor);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading;
//Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading*x + 0.5f + baselineOffset);
}
//Close our Path and Stroke (draw) it
CGContextClosePath(context);
CGContextStrokePath(context);
}
//its a view controller class and here i imported NotesView here
#import "NotesViewController.h"
#interface NotesViewController ()
#end
#implementation NotesViewController
// i load the textView frame whatever i created class above
- (void)loadView {
[super loadView];
CGSize result = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [UIScreen mainScreen].scale;
result = CGSizeMake(result.width*scale, result.height * scale);
if (result.height==1136)
{
_TextView = [[NoteView alloc] initWithFrame:CGRectMake(29,50,266,430)];
backgroundView.frame=CGRectMake(10,32,300,450);
}
else
{
_TextView = [[NoteView alloc] initWithFrame:CGRectMake(29,50,266,340)];
backgroundView.frame=CGRectMake(10,32,300,360);
}
[self.view addSubview:_TextView];
_TextView.delegate = self;
UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(30,40,1,backgroundView.frame.size.height-5)];
lineView.backgroundColor = [UIColor brownColor];
lineView.alpha=0.3;
[self.view addSubview:lineView];
UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(32,40,1,backgroundView.frame.size.height-5)];
lineView1.backgroundColor = [UIColor brownColor];
lineView1.alpha=0.3;
[self.view addSubview:lineView1];
}
}
}
// in view did load i set the delegate and code for cursor position
- (void)viewDidLoad
{
[super viewDidLoad];
// setting delegate here
_TextView.delegate=self;
_TextView.editable = YES;
[_TextView setSelectedRange:NSMakeRange(10, 0)];
}
I write all the delegate methods for Textview and ScrollView of Textview I the cursor positon is starts the vertical line after.... I'm not expressed well please understand based on images... I want cursor position... I want to set my Textview with real note application in iPhone.. I add Textview to ViewController all works well but cursor stats starting position... I want to cursor position always horizontal line........ Try to give solution based on the images..
Do it like this image.
Here you have to set the position of your textview in your VC so it will come after the horizontal line.

Display a progress bar inside a UITextField object

How can one draw a progressbar inside a UITextField ? I have tested two ways so far.
1. Add a UIProgressView object as a subview of the UITextField object.
UIProgressView* progressView = [[UIProgressView alloc] init];
[aUITextField addSubview:progressView];
progressView.progress = 0.5;
[progressView release];
2. Subclass UITextfield and override drawRect:.
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
[self setBackgroundColor:[UIColor clearColor]];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
[[UIColor orangeColor] setFill];
[[UIBezierPath bezierPathWithOvalInRect:rect] fill];
}
Both approaches didn't work. Do you see any problem with these approaches? And how can I make this work?
I am not sure adding the UIProgressView as a subview of a UITextField object will be useful as you can't change the frame of the progress view.
Subclassing seems to be the right approach. Here is what I could come up with. Check if it is useful to you.
ProgressField.h
#interface ProgressField : UITextField {
}
#property (nonatomic, assign) CGFloat progress;
#property (nonatomic, retain) UIColor * progressColor;
#end
ProgressField.m
#implementation ProgressField
#synthesize progress;
#synthesize progressColor;
- (void)setProgress:(CGFloat)aProgress {
if ( aProgress < 0.0 || aProgress > 1.0 ) {
return;
}
progress = aProgress;
CGRect progressRect = CGRectZero;
CGSize progressSize = CGSizeMake(progress * CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
progressRect.size = progressSize;
// Create the background image
UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, self.bounds);
CGContextSetFillColorWithColor(context, [self progressColor].CGColor);
CGContextFillRect(context, progressRect);
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[super setBackground:image];
}
- (void)setBackground:(UIImage *)background {
// NO-OP
}
- (UIImage *)background {
return nil;
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setBorderStyle:UITextBorderStyleBezel];
}
return self;
}
This doesn't seem to work with UITextFields with borderStyle set to UITextBorderStyleRoundedRect.
UIProgressView* progressView = [[UIProgressView alloc] init];
progressView.frame = aUITextField.frame;// you can give even set the frame of your own using CGRectMake();
[aUITextField addSubview:progressView];
progressView.progress = 0.5;
[progressView release];
Set the progressview's frame.
Here I think you have to add progressView as subview to self.view , just set progressView's frame according to size that will fit in to UITextField , and make set center of progressview to center of UITextField .
hope it will help you.

How can I change the color of pagination dots of UIPageControl?

I am developing an application in which I want to change either color or image of UIPageControl pagination dots. How can I change it? Is it possible to customize UIpageControl on above scenario?
UPDATE:
This answer is 6 years old and very outdated, but it's still attracting votes and comments. Ever since iOS 6.0 you should be using the pageIndicatorTintColor and currentPageIndicatorTintColor properties on UIPageControl.
ORIGINAL ANSWER:
I ran into this problem today and decided to write my own simple replacement class.
It's a sublassed UIView that uses Core Graphics to render the dots in the colors you specify.
You use the exposed properties to customize and control it.
If you want to you can register a delegate object to get notifications when the user taps on one of the little page dots. If no delegate is registered then the view will not react to touch input.
It's completely fresh from the oven, but seems to work. Let me know if you run into any problems with it.
Future improvements:
Resize the dots to fit the current
bounds if there are too many.
Don't redraw the entire view in drawRect:
Example use:
CGRect f = CGRectMake(0, 0, 320, 20);
PageControl *pageControl = [[[PageControl alloc] initWithFrame:f] autorelease];
pageControl.numberOfPages = 10;
pageControl.currentPage = 5;
pageControl.delegate = self;
[self addSubview:pageControl];
Header file:
//
// PageControl.h
//
// Replacement for UIPageControl because that one only supports white dots.
//
// Created by Morten Heiberg <morten#heiberg.net> on November 1, 2010.
//
#import <UIKit/UIKit.h>
#protocol PageControlDelegate;
#interface PageControl : UIView
{
#private
NSInteger _currentPage;
NSInteger _numberOfPages;
UIColor *dotColorCurrentPage;
UIColor *dotColorOtherPage;
NSObject<PageControlDelegate> *delegate;
//If ARC use __unsafe_unretained id delegate;
}
// Set these to control the PageControl.
#property (nonatomic) NSInteger currentPage;
#property (nonatomic) NSInteger numberOfPages;
// Customize these as well as the backgroundColor property.
#property (nonatomic, retain) UIColor *dotColorCurrentPage;
#property (nonatomic, retain) UIColor *dotColorOtherPage;
// Optional delegate for callbacks when user taps a page dot.
#property (nonatomic, retain) NSObject<PageControlDelegate> *delegate;
#end
#protocol PageControlDelegate<NSObject>
#optional
- (void)pageControlPageDidChange:(PageControl *)pageControl;
#end
Implementation file:
//
// PageControl.m
//
// Replacement for UIPageControl because that one only supports white dots.
//
// Created by Morten Heiberg <morten#heiberg.net> on November 1, 2010.
//
#import "PageControl.h"
// Tweak these or make them dynamic.
#define kDotDiameter 7.0
#define kDotSpacer 7.0
#implementation PageControl
#synthesize dotColorCurrentPage;
#synthesize dotColorOtherPage;
#synthesize delegate;
- (NSInteger)currentPage
{
return _currentPage;
}
- (void)setCurrentPage:(NSInteger)page
{
_currentPage = MIN(MAX(0, page), _numberOfPages-1);
[self setNeedsDisplay];
}
- (NSInteger)numberOfPages
{
return _numberOfPages;
}
- (void)setNumberOfPages:(NSInteger)pages
{
_numberOfPages = MAX(0, pages);
_currentPage = MIN(MAX(0, _currentPage), _numberOfPages-1);
[self setNeedsDisplay];
}
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
// Default colors.
self.backgroundColor = [UIColor clearColor];
self.dotColorCurrentPage = [UIColor blackColor];
self.dotColorOtherPage = [UIColor lightGrayColor];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipedRight:)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
[self addGestureRecognizer:swipeRight];
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipedLeft:)];
[swipe setDirection:UISwipeGestureRecognizerDirectionLeft];
[self addGestureRecognizer:swipe];
}
return self;
}
-(void) swipedLeft:(UISwipeGestureRecognizer *) recognizer
{
self.currentPage++;
}
-(void) swipedRight:(UISwipeGestureRecognizer *) recognizer
{
self.currentPage--;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context, true);
CGRect currentBounds = self.bounds;
CGFloat dotsWidth = self.numberOfPages*kDotDiameter + MAX(0, self.numberOfPages-1)*kDotSpacer;
CGFloat x = CGRectGetMidX(currentBounds)-dotsWidth/2;
CGFloat y = CGRectGetMidY(currentBounds)-kDotDiameter/2;
for (int i=0; i<_numberOfPages; i++)
{
CGRect circleRect = CGRectMake(x, y, kDotDiameter, kDotDiameter);
if (i == _currentPage)
{
CGContextSetFillColorWithColor(context, self.dotColorCurrentPage.CGColor);
}
else
{
CGContextSetFillColorWithColor(context, self.dotColorOtherPage.CGColor);
}
CGContextFillEllipseInRect(context, circleRect);
x += kDotDiameter + kDotSpacer;
}
}
- (void)dealloc
{
[dotColorCurrentPage release];
[dotColorOtherPage release];
[delegate release];
[super dealloc];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!self.delegate) return;
CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
CGFloat dotSpanX = self.numberOfPages*(kDotDiameter + kDotSpacer);
CGFloat dotSpanY = kDotDiameter + kDotSpacer;
CGRect currentBounds = self.bounds;
CGFloat x = touchPoint.x + dotSpanX/2 - CGRectGetMidX(currentBounds);
CGFloat y = touchPoint.y + dotSpanY/2 - CGRectGetMidY(currentBounds);
if ((x<0) || (x>dotSpanX) || (y<0) || (y>dotSpanY)) return;
self.currentPage = floor(x/(kDotDiameter+kDotSpacer));
if ([self.delegate respondsToSelector:#selector(pageControlPageDidChange:)])
{
[self.delegate pageControlPageDidChange:self];
}
}
#end
In iOS 6 you can set the tint color of UIPageControl:
There are 2 new properties:
pageIndicatorTintColor
currentPageIndicatorTintColor
You can also use the appearance API to change the tint color of all page indicators.
If you are targeting iOS 5 make sure it doesn't crash:
if ([pageControl respondsToSelector:#selector(setPageIndicatorTintColor:)]) {
pageControl.pageIndicatorTintColor = [UIColor whiteColor];
}
pageControl.pageIndicatorTintColor = [UIColor redColor];
pageControl.currentPageIndicatorTintColor = [UIColor redColor];
works for iOS6
In case anyone wants an ARC / modern version of it (no need to redefine properties as ivar, no dealloc, and works with Interface Builder) :
#import <UIKit/UIKit.h>
#protocol PageControlDelegate;
#interface PageControl : UIView
// Set these to control the PageControl.
#property (nonatomic) NSInteger currentPage;
#property (nonatomic) NSInteger numberOfPages;
// Customize these as well as the backgroundColor property.
#property (nonatomic, strong) UIColor *dotColorCurrentPage;
#property (nonatomic, strong) UIColor *dotColorOtherPage;
// Optional delegate for callbacks when user taps a page dot.
#property (nonatomic, weak) NSObject<PageControlDelegate> *delegate;
#end
#protocol PageControlDelegate<NSObject>
#optional
- (void)pageControlPageDidChange:(PageControl *)pageControl;
#end
PageControl.m :
#import "PageControl.h"
// Tweak these or make them dynamic.
#define kDotDiameter 7.0
#define kDotSpacer 7.0
#implementation PageControl
#synthesize dotColorCurrentPage;
#synthesize dotColorOtherPage;
#synthesize currentPage;
#synthesize numberOfPages;
#synthesize delegate;
- (void)setCurrentPage:(NSInteger)page
{
currentPage = MIN(MAX(0, page), self.numberOfPages-1);
[self setNeedsDisplay];
}
- (void)setNumberOfPages:(NSInteger)pages
{
numberOfPages = MAX(0, pages);
currentPage = MIN(MAX(0, self.currentPage), numberOfPages-1);
[self setNeedsDisplay];
}
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
// Default colors.
self.backgroundColor = [UIColor clearColor];
self.dotColorCurrentPage = [UIColor blackColor];
self.dotColorOtherPage = [UIColor lightGrayColor];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder])
{
self.dotColorCurrentPage = [UIColor blackColor];
self.dotColorOtherPage = [UIColor lightGrayColor];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context, true);
CGRect currentBounds = self.bounds;
CGFloat dotsWidth = self.numberOfPages*kDotDiameter + MAX(0, self.numberOfPages-1)*kDotSpacer;
CGFloat x = CGRectGetMidX(currentBounds)-dotsWidth/2;
CGFloat y = CGRectGetMidY(currentBounds)-kDotDiameter/2;
for (int i=0; i<self.numberOfPages; i++)
{
CGRect circleRect = CGRectMake(x, y, kDotDiameter, kDotDiameter);
if (i == self.currentPage)
{
CGContextSetFillColorWithColor(context, self.dotColorCurrentPage.CGColor);
}
else
{
CGContextSetFillColorWithColor(context, self.dotColorOtherPage.CGColor);
}
CGContextFillEllipseInRect(context, circleRect);
x += kDotDiameter + kDotSpacer;
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!self.delegate) return;
CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
CGFloat dotSpanX = self.numberOfPages*(kDotDiameter + kDotSpacer);
CGFloat dotSpanY = kDotDiameter + kDotSpacer;
CGRect currentBounds = self.bounds;
CGFloat x = touchPoint.x + dotSpanX/2 - CGRectGetMidX(currentBounds);
CGFloat y = touchPoint.y + dotSpanY/2 - CGRectGetMidY(currentBounds);
if ((x<0) || (x>dotSpanX) || (y<0) || (y>dotSpanY)) return;
self.currentPage = floor(x/(kDotDiameter+kDotSpacer));
if ([self.delegate respondsToSelector:#selector(pageControlPageDidChange:)])
{
[self.delegate pageControlPageDidChange:self];
}
}
#end
The answer provided by Heiberg works really well, however the page control does not behave exactly like the one by apple.
If you want the page control to behave like the one from apple does (always increment the current page by one if you touch the second half, otherwise decrease by one), try this touchesBegan-method instead:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];
CGRect currentBounds = self.bounds;
CGFloat x = touchPoint.x - CGRectGetMidX(currentBounds);
if(x<0 && self.currentPage>=0){
self.currentPage--;
[self.delegate pageControlPageDidChange:self];
}
else if(x>0 && self.currentPage<self.numberOfPages-1){
self.currentPage++;
[self.delegate pageControlPageDidChange:self];
}
}
Add the following code to DidFinishLauch in AppDelegate,
UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
pageControl.backgroundColor = [UIColor whiteColor];
Hope this will help.
In Swift, this code inside the UIPageViewController is getting a reference to the page indicator and setting its properties
override func viewDidLoad() {
super.viewDidLoad()
//Creating the proxy
let pageControl = UIPageControl.appearance()
//Customizing
pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControl.currentPageIndicatorTintColor = UIColor.darkGrayColor()
//Setting the background of the view controller so the dots wont be on a black background
self.view.backgroundColor = UIColor.whiteColor()
}
use this for coding
if ([pageControl respondsToSelector:#selector(setPageIndicatorTintColor:)]) {
pageControl.pageIndicatorTintColor = [UIColor whiteColor];
}
or from storyboard you can change from current page tint
Adding to existing answers, it can be done like,
You can fix it with ease by adding the following code to your appdelegate.m file in your didFinishLaunchingWithOptions method:
UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
pageControl.backgroundColor = [UIColor whiteColor]
This is worked for me in iOS 7.
pageControl.pageIndicatorTintColor = [UIColor purpleColor];
pageControl.currentPageIndicatorTintColor = [UIColor magentaColor];
It's easy with Swift 1.2:
UIPageControl.appearance().pageIndicatorTintColor = UIColor.lightGrayColor()
UIPageControl.appearance().currentPageIndicatorTintColor = UIColor.redColor()
In cased of Swift 2.0 and up, the below code will work:
pageControl.pageIndicatorTintColor = UIColor.whiteColor()
pageControl.currentPageIndicatorTintColor = UIColor.redColor()
#Jasarien I think you can subclass UIPageControll, line picked from apple doc only "Subclasses that customize the appearance of the page control can use this method to resize the page control when the page count changes" for the method sizeForNumberOfPages:
You could also use Three20 Library that contains a styleable PageControl and dozens of other helpful UI Controls and Abstractions.
It's not possible using the iPhone SDK from an official standpoint. You might be able to do it using private methods, but that will be a barrier to getting onto the app store.
The only other safe solution is to create yout own page control which shpuldnt be too difficult given that the page control simply displays what page is currently shown in a scroll view.
myView.superview.tintColor = [UIColor colorWithRed:1.0f
green:1.0f blue:1.0f alpha:1.0f];

How to make a subview tint a portion of the screen on the iPhone?

I would like to write a UIView subclass that, among other things, colors whatever's underneath it a certain color. This is what I've come up with, but it unfortunately doesn't seem to work correctly:
#import <UIKit/UIKit.h>
#class MyOtherView;
#interface MyView : UIView
{
MyOtherView *subview;
}
#end
#implementation MyView
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
frame.origin.x += 100.0;
frame.origin.y += 100.0;
frame.size.width = frame.size.height = 200.0;
subview = [[MyOtherView alloc] initWithFrame:frame];
[self addSubview:subview];
[subview release];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Draw a background to test out on
UIImage *image = [UIImage imageNamed:#"somepic.png"];
[image drawAtPoint:rect.origin];
const CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blueColor] setFill];
rect.size.width = rect.size.height = 200.0;
CGContextFillRect(ctx, rect);
}
#end
#interface MyOtherView : UIView
#end
#implementation MyOtherView
- (void)drawRect:(CGRect)rect
{
// This should tint "MyView" but it doesn't.
const CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeScreen);
[[UIColor redColor] setFill];
CGContextFillRect(ctx, rect);
CGContextRestoreGState(ctx);
}
#end
I want "MyOtherView" to color "MyView" red where it overlaps, but instead it just draws an opaque red block onto it. However, this seems work fine if I copy the -drawRect: function from "MyOtherView" and append it to the one in "MyView" (this took me quite a headache to finally realize). Anyone know what I'm doing wrong? Is it even possible to do this, or should I be approaching it differently?
I think you're over-thinking this. Overlay one view over the other, and set the alpha of the top view to 0.5. You will also need to set opaque to NO.
If you set the background color of the view appropriately, you won't even need to override drawRect.
Might want to check out this SO question.