I want to add line numbers to my UITextView.
Do I have to write my own UI-Element, or is there an other solution?
I accomplished this by subclassing UIView and overriding the drawRect: method like so:
#define TXT_VIEW_INSETS 8.0 // The default insets for a UITextView is 8.0 on all sides
#implementation NumberedTextView
#synthesize lineNumbers;
#synthesize delegate;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setContentMode:UIViewContentModeRedraw];
internalScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
[internalScrollView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[internalScrollView setBackgroundColor:[UIColor clearColor]];
[internalScrollView setClipsToBounds:YES];
[internalScrollView setScrollsToTop:YES];
[internalScrollView setContentSize:self.bounds.size];
[internalScrollView setContentMode:UIViewContentModeLeft];
[internalScrollView setDelegate:self];
[internalScrollView setBounces:NO];
internalTextView = [[UITextView alloc] initWithFrame:self.bounds];
[internalTextView setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[internalTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
[internalTextView setSpellCheckingType:UITextSpellCheckingTypeNo];
[internalTextView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[internalTextView setBackgroundColor:[UIColor clearColor]];
[internalTextView setClipsToBounds:YES];
[internalTextView setScrollsToTop:NO];
[internalTextView setContentMode:UIViewContentModeLeft];
[internalTextView setDelegate:self];
[internalTextView setBounces:NO];
[internalScrollView addSubview:internalTextView];
[self addSubview:internalScrollView];
}
return self;
}
- (void)drawRect:(CGRect)rect {
if (self.lineNumbers) {
[[internalTextView textColor] set];
CGFloat xOrigin, yOrigin, width/*, height*/;
uint numberOfLines = (internalTextView.contentSize.height + internalScrollView.contentSize.height) / internalTextView.font.lineHeight;
for (uint x = 0; x < numberOfLines; ++x) {
NSString *lineNum = [NSString stringWithFormat:#"%d:", x];
xOrigin = CGRectGetMinX(self.bounds);
yOrigin = ((internalTextView.font.pointSize + abs(internalTextView.font.descender)) * x) + TXT_VIEW_INSETS - internalScrollView.contentOffset.y;
width = [lineNum sizeWithFont:internalTextView.font].width;
// height = internalTextView.font.lineHeight;
[lineNum drawAtPoint:CGPointMake(xOrigin, yOrigin) withFont:internalTextView.font];
}
CGRect tvFrame = [internalTextView frame];
tvFrame.size.width = CGRectGetWidth(internalScrollView.bounds) - width;
tvFrame.size.height = MAX(internalTextView.contentSize.height, CGRectGetHeight(internalScrollView.bounds));
tvFrame.origin.x = width;
[internalTextView setFrame:tvFrame];
tvFrame.size.height -= TXT_VIEW_INSETS; // This fixed a weird content size problem that I've forgotten the specifics of.
[internalScrollView setContentSize:tvFrame.size];
}
}
#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
[self setNeedsDisplay];
return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
[self setNeedsDisplay];
}
- (void)textViewDidChangeSelection:(UITextView *)textView {
[self setNeedsDisplay];
}
#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[self setNeedsDisplay];
}
There's nothing built-in for this. You'll have to do it yourself.
Related
I have made a little test to drag views in a UIScrollView to UIView where I can call any action.
I'm trying to be able to make the image I made in the UIScrollView Draggable. I have not been able to make this work.
I was able to create test views which are not images that are able to drag.
TestViewController.h
#import "JDDroppableView.h"
#interface TestViewController : UIViewController <JDDroppableViewDelegate>
{
UIScrollView* mScrollView;
UIView* mDropTarget;
UIImageView *images;
UIImageView *image;
CGPoint mLastPosition;
}
- (void) relayout;
- (void) addView: (id) sender;
- (void) scrollToBottomAnimated: (BOOL) animated;
#property (nonatomic, retain) IBOutlet UIImageView *images;
#property (nonatomic, retain) IBOutlet UIImageView *image;
#end
TestViewController.m
#import "TestViewController.h"
#import "JDDroppableView.h"
#import <QuartzCore/QuartzCore.h>
// setup view vars
static NSInteger sDROPVIEW_MARGIN = 3;
static CGFloat sCOUNT_OF_VIEWS_HORICONTALLY = 1.0;
static CGFloat sCOUNT_OF_VIEWS_VERTICALLY = 1.0;
#implementation TestViewController
#synthesize images;
#synthesize image;
- (void)loadView
{
[super loadView];
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
// increase viewcount on ipad
if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
sCOUNT_OF_VIEWS_HORICONTALLY = 0;
sCOUNT_OF_VIEWS_VERTICALLY = 0;
}
// add button
UIButton* button = [UIButton buttonWithType: UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"002.jpg"] forState:UIControlStateNormal];
button.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
[button setTitle: #"+" forState: UIControlStateNormal];
[button addTarget: self action: #selector(addView:) forControlEvents: UIControlEventTouchUpInside];
button.backgroundColor = [UIColor colorWithRed: 0.75 green: 0.2 blue: 0 alpha: 1.0];
button.layer.cornerRadius = 5.0;
button.showsTouchWhenHighlighted = YES;
button.adjustsImageWhenHighlighted = YES;
button.frame = CGRectMake(20,
self.view.frame.size.height - 52,
self.view.frame.size.width - 40, // width
32); // height
[self.view addSubview: button];
// drop target
mDropTarget = [[UIView alloc] init];
mDropTarget.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
mDropTarget.backgroundColor = [UIColor orangeColor];
mDropTarget.frame = CGRectMake(0, 0, 30, 30);
mDropTarget.center = CGPointMake(self.view.frame.size.width/2, button.frame.origin.y - 50);
mDropTarget.layer.cornerRadius = 15;
[self.view addSubview: mDropTarget];
[mDropTarget release];
// scrollview
mScrollView = [[UIScrollView alloc] init];
mScrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
mScrollView.backgroundColor = [UIColor colorWithRed: 0.75 green: 0.2 blue: 0 alpha: 1.0];
mScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
mScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 5, 5, 5);
mScrollView.contentInset = UIEdgeInsetsMake(6, 6, 6, 6);
mScrollView.layer.cornerRadius = 5.0;
mScrollView.frame = CGRectMake(20,20, self.view.frame.size.width - 40, mDropTarget.center.y - 70);
mScrollView.userInteractionEnabled = NO;
mScrollView.canCancelContentTouches = NO;
[self.view addSubview: mScrollView];
[mScrollView release];
// animate some draggable views in
int numberOfViews = sCOUNT_OF_VIEWS_HORICONTALLY*floor(sCOUNT_OF_VIEWS_VERTICALLY) + 2;
CGFloat animationTimePerView = 0.15;
for (int i = 0; i < numberOfViews; i++) {
[self performSelector: #selector(addView:) withObject: nil afterDelay: i*animationTimePerView];
if (i%(int)sCOUNT_OF_VIEWS_HORICONTALLY==0) {
[self performSelector: #selector(scrollToBottomAnimated:) withObject: [NSNumber numberWithBool: YES] afterDelay: i*animationTimePerView];
}
}
CGRect myImageRect = CGRectMake(0, 0, 320, 100);
image = [[UIImageView alloc] initWithFrame:myImageRect];
[image setImage:[UIImage imageNamed:#"002.jpg"]];
[image setUserInteractionEnabled:YES];
[self.view addSubview:image];
[mScrollView addSubview:image];
// reenable userinteraction after animation ended
[mScrollView performSelector: #selector(setUserInteractionEnabled:) withObject: [NSNumber numberWithBool: YES] afterDelay: numberOfViews*animationTimePerView];
}
#pragma layout
- (void) relayout
{
// cancel all animations
[mScrollView.layer removeAllAnimations];
for (UIView* subview in mScrollView.subviews)
[subview.layer removeAllAnimations];
// setup new animation
[UIView beginAnimations: #"drag" context: nil];
// init calculation vars
float posx = 0;
float posy = 0;
CGRect frame = CGRectZero;
mLastPosition = CGPointMake(0, -100);
CGFloat contentWidth = mScrollView.contentSize.width - mScrollView.contentInset.left - mScrollView.contentInset.right;
// iterate through all subviews
for (UIView* subview in mScrollView.subviews)
{
// ignore scroll indicators
if (!subview.userInteractionEnabled) {
continue;
}
// create new position
frame = subview.frame;
frame.origin.x = posx;
frame.origin.y = posy;
// update frame (if it did change)
if (frame.origin.x != subview.frame.origin.x ||
frame.origin.y != subview.frame.origin.y) {
subview.frame = frame;
}
// save last position
mLastPosition = CGPointMake(posx, posy);
// add size and margin
posx += frame.size.width + sDROPVIEW_MARGIN;
// goto next row if needed
if (posx > mScrollView.frame.size.width - mScrollView.contentInset.left - mScrollView.contentInset.right)
{
posx = 0;
posy += frame.size.height + sDROPVIEW_MARGIN;
}
}
// fix last posy for correct contentSize
if (posx != 0) {
posy += frame.size.height;
} else {
posy -= sDROPVIEW_MARGIN;
}
// update content size
mScrollView.contentSize = CGSizeMake(contentWidth, posy);
[UIView commitAnimations];
}
- (void) addView: (id) sender
{
CGFloat contentWidth = mScrollView.frame.size.width - mScrollView.contentInset.left - mScrollView.contentInset.right;
CGFloat contentHeight = mScrollView.frame.size.height - mScrollView.contentInset.top;
CGSize size = CGSizeMake(((contentWidth-sDROPVIEW_MARGIN*(sCOUNT_OF_VIEWS_HORICONTALLY-1))/sCOUNT_OF_VIEWS_HORICONTALLY),
floor((contentHeight-sDROPVIEW_MARGIN*(sCOUNT_OF_VIEWS_VERTICALLY-1))/sCOUNT_OF_VIEWS_VERTICALLY));
JDDroppableView * dropview = [[JDDroppableView alloc] initWithDropTarget: mDropTarget];
dropview.backgroundColor = [UIColor blackColor];
dropview.layer.cornerRadius = 3.0;
dropview.frame = CGRectMake(mLastPosition.x, mLastPosition.y, size.width, size.height);
dropview.delegate = self;
[mScrollView addSubview: dropview];
[dropview release];
[self relayout];
// scroll to bottom, if added manually
if ([sender isKindOfClass: [UIButton class]]) {
[self scrollToBottomAnimated: YES];
}
}
- (void) scrollToBottomAnimated: (BOOL) animated
{
[mScrollView.layer removeAllAnimations];
CGFloat bottomScrollPosition = mScrollView.contentSize.height;
bottomScrollPosition -= mScrollView.frame.size.height;
bottomScrollPosition += mScrollView.contentInset.top;
bottomScrollPosition = MAX(-mScrollView.contentInset.top,bottomScrollPosition);
CGPoint newOffset = CGPointMake(-mScrollView.contentInset.left, bottomScrollPosition);
if (newOffset.y != mScrollView.contentOffset.y) {
[mScrollView setContentOffset: newOffset animated: animated];
}
}
#pragma -
#pragma droppabe view delegate
- (BOOL) shouldAnimateDroppableViewBack: (JDDroppableView *)view wasDroppedOnTarget: (UIView *)target
{
[self droppableView: view leftTarget: target];
CGRect frame = view.frame;
frame.size.width *= 0.3;
frame.size.height *= 0.3;
frame.origin.x += (view.frame.size.width-frame.size.width)/2;
frame.origin.y += (view.frame.size.height-frame.size.height)/2;
[UIView beginAnimations: #"drag" context: nil];
[UIView setAnimationDelegate: view];
[UIView setAnimationDidStopSelector: #selector(removeFromSuperview)];
view.frame = frame;
view.center = target.center;
[UIView commitAnimations];
[self relayout];
[mScrollView flashScrollIndicators];
return NO;
}
- (void) droppableViewBeganDragging:(JDDroppableView *)view
{
[UIView beginAnimations: #"drag" context: nil];
view.backgroundColor = [UIColor colorWithRed: 1 green: 0.5 blue: 0 alpha: 1];
view.alpha = 0.8;
[UIView commitAnimations];
}
- (void) droppableView:(JDDroppableView *)view enteredTarget:(UIView *)target
{
target.transform = CGAffineTransformMakeScale(1.5, 1.5);
target.backgroundColor = [UIColor greenColor];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"image Collided"
// message:#"FuckYea"
// delegate:nil
// cancelButtonTitle:#"Reset!"
// otherButtonTitles:nil];
//[alert show];
CGRect myImageRect = CGRectMake(0, 0, 320, 100);
images = [[UIImageView alloc] initWithFrame:myImageRect];
[images setImage:[UIImage imageNamed:#"002.jpg"]];
[self.view addSubview:images];
}
- (void) droppableView:(JDDroppableView *)view leftTarget:(UIView *)target
{
target.transform = CGAffineTransformMakeScale(1.0, 1.0);
target.backgroundColor = [UIColor orangeColor];
}
- (void) droppableViewEndedDragging:(JDDroppableView *)view
{
[UIView beginAnimations: #"drag" context: nil];
view.backgroundColor = [UIColor blackColor];
view.alpha = 1.0;
[UIView commitAnimations];
}
#end
JDDroppableView.h
#class JDDroppableView;
#protocol JDDroppableViewDelegate <NSObject>
#optional
- (void) droppableViewBeganDragging: (JDDroppableView*) view;
- (void) droppableViewDidMove: (JDDroppableView*) view;
- (void) droppableView: (JDDroppableView*) view enteredTarget: (UIView*) target;
- (void) droppableView: (JDDroppableView*) view leftTarget: (UIView*) target;
- (BOOL) shouldAnimateDroppableViewBack: (JDDroppableView*) view wasDroppedOnTarget: (UIView*) target;
- (void) droppableViewEndedDragging: (JDDroppableView*) view;
#end
#interface JDDroppableView : UIView
{
UIView * mDropTarget;
UIView * mOuterView;
UIScrollView * mScrollView;
BOOL mIsDragging;
BOOL mIsOverTarget;
CGPoint mOriginalPosition;
}
#property (nonatomic, assign) id<JDDroppableViewDelegate> delegate;
- (id) initWithFrame:(CGRect)frame;
- (id) initWithDropTarget:(UIView*)target;
#end
JDDroppableView.m
#import "JDDroppableView.h"
#interface JDDroppableView (hidden)
- (void) beginDrag;
- (void) dragAtPosition: (UITouch *) touch;
- (void) endDrag;
- (void) changeSuperView;
- (BOOL) handleDroppedView;
#end
#implementation JDDroppableView
#synthesize delegate = _delegate;
- (id)init
{
return [self initWithFrame: [UIApplication sharedApplication].keyWindow.frame];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
mIsDragging = NO;
mIsOverTarget = NO;
}
return self;
}
- (id) initWithDropTarget: (UIView *) target;
{
self = [self init];
if (self != nil) {
mDropTarget = target;
}
return self;
}
#pragma mark touch handling
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self beginDrag];
[self dragAtPosition: [touches anyObject]];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[self dragAtPosition: [touches anyObject]];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self endDrag];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self endDrag];
}
#pragma mark dragging logic
- (void) beginDrag
{
mIsDragging = YES;
if ([_delegate respondsToSelector: #selector(droppableViewBeganDragging:)]) {
[_delegate droppableViewBeganDragging: self];
};
mOriginalPosition = self.center;
[self changeSuperView];
}
- (void) dragAtPosition: (UITouch *) touch
{
[UIView beginAnimations: #"drag" context: nil];
self.center = [touch locationInView: self.superview];
[UIView commitAnimations];
if ([_delegate respondsToSelector: #selector(droppableViewDidMove:)]) {
[_delegate droppableViewDidMove:self];
}
if (mDropTarget) {
CGRect intersect = CGRectIntersection(self.frame, mDropTarget.frame);
if (intersect.size.width > 10 || intersect.size.height > 10)
{
if (!mIsOverTarget)
{
mIsOverTarget = YES;
if ([_delegate respondsToSelector: #selector(droppableView:enteredTarget:)]) {
[_delegate droppableView: self enteredTarget: mDropTarget];
}
}
}
else if (mIsOverTarget)
{
mIsOverTarget = NO;
if ([_delegate respondsToSelector: #selector(droppableView:leftTarget:)]) {
[_delegate droppableView: self leftTarget: mDropTarget];
}
}
}
}
- (void) endDrag
{
mIsOverTarget = NO;
if([_delegate respondsToSelector: #selector(droppableViewEndedDragging:)]) {
[_delegate droppableViewEndedDragging: self];
}
if (mDropTarget) {
CGRect intersect = CGRectIntersection(self.frame, mDropTarget.frame);
if (intersect.size.width > 10 || intersect.size.height > 10) {
if([self handleDroppedView]) {
mIsDragging = NO;
return;
}
}
}
[self changeSuperView];
mIsDragging = NO; // this needs to be after superview change
[UIView beginAnimations: #"drag" context: nil];
self.center = mOriginalPosition;
[UIView commitAnimations];
}
- (BOOL) handleDroppedView
{
if (mDropTarget && [_delegate respondsToSelector: #selector(shouldAnimateDroppableViewBack:wasDroppedOnTarget:)]) {
return ![_delegate shouldAnimateDroppableViewBack: self wasDroppedOnTarget: mDropTarget];
}
return NO;
}
#pragma mark superview handling
- (void)willMoveToSuperview:(id)newSuperview
{
if (!mIsDragging && [newSuperview isKindOfClass: [UIScrollView class]]) {
mScrollView = newSuperview;
mOuterView = mScrollView.superview;
}
}
- (void) changeSuperView
{
if (!mScrollView) {
[self.superview bringSubviewToFront: self];
return;
}
UIView * tmp = self.superview;
[self removeFromSuperview];
[mOuterView addSubview: self];
mOuterView = tmp;
// set new position
CGPoint ctr = self.center;
if (mOuterView == mScrollView) {
ctr.x += mScrollView.frame.origin.x - mScrollView.contentOffset.x;
ctr.y += mScrollView.frame.origin.y - mScrollView.contentOffset.y;
} else {
ctr.x -= mScrollView.frame.origin.x - mScrollView.contentOffset.x;
ctr.y -= mScrollView.frame.origin.y - mScrollView.contentOffset.y;
}
self.center = ctr;
}
#end
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
UIWindow* mWindow;
TestViewController* mViewController;
}
#end
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
mWindow = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
mWindow.backgroundColor = [UIColor whiteColor];
TestViewController* viewController = [[TestViewController alloc] init];
[mWindow addSubview: viewController.view];
[mWindow makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[mWindow release];
[mViewController release];
[super dealloc];
}
#end
Any help is much appreciated.
Thank you.
According to Apple's documentation
New image view objects are configured to disregard user events by
default. If you want to handle events in a custom subclass of
UIImageView, you must explicitly change the value of the
userInteractionEnabled property to YES after initializing the object.
You need to set userInteractionEnabled to YES on your UIImageView like this:
[image setUserInteractionEnabled:YES];
Hope this help.
You posted the complete example code of https://github.com/jaydee3/JDDroppableView/.
Perhaps you just ask a single question and refer to the project. But to use it for UIImageViews, you need to alloc init a JDDroppableView and put your imageView on it.
UIImageView *imageView = [[UIImageView alloc] initWithImage:...];
imageView.autoresizingMask = UIAutoresizingFlexibleWidth | UIAutoresizingFlexibleHeight;
JDDroppableView *droppableView = [[JDDroppableView alloc] initWithFrame:imageView.bounds];
[droppableView addSubview:imageView];
I need to create the UI component shown in the image below, and also i need to know;
What is it called? (The grey colored box)
How do i add an image or any other UI component to it?
Is there any sample code or tutorial available creating this?
The image
In answer to your questions:
1) What is it called?
I'd go with UIView - with the cornerRadius of it's CALayer set, and a semi-transparent background colour.
2) How do i add an image or any other UI component to it?
[myview addSubview: someSubview];
3) Is there any sample code or tutorial available creating this?
It really sounds like you need to read the Apple docs.
I think that's MBProgressHUD.
https://github.com/jdg/MBProgressHUD
MBProgressHud have no progress bar. I've created one by using PDColoredProgressView and Three20
It looks like this:
and goes that way:
.h file
#import <UIKit/UIKit.h>
#import "PDColoredProgressView.h"
#interface SVProgressHudView : UIView<PDColoredProgressViewDelegate>{
UIView* bgView;
UILabel* _titleLabel;
PDColoredProgressView* _progress;
UILabel* _percentLabel;
UILabel* _subtitleLabel;
NSUInteger _numOfSteps;
NSUInteger _currentStep;
CGFloat _currentStepProgress;
CGFloat _oneStepPart;
CGFloat _extraStepPart;
BOOL _removeFromSuperViewOnHide;
BOOL _extraStep;
UIButton* _closeButton;
}
#property (nonatomic, assign)BOOL removeFromSuperViewOnHide;
+(SVProgressHudView *)hudAddedTo:(UIView *)view withTitle:(NSString*)title numberOfSteps:(NSUInteger)numberOfSteps extraStep:(BOOL)exrta;
+(BOOL)isThereHudAddedToView:(UIView*)view;
-(id)initWithFrame:(CGRect)frame title:(NSString*)title numberOfSteps:(NSUInteger)numberOfSteps extraStep:(BOOL)exrta;
-(void)show:(BOOL)animated;
-(void)hide:(BOOL)animated;
-(void)setCurrentStepProgress:(CGFloat)currentProgress animated:(BOOL)animated;
-(void)setCurrentStep:(NSUInteger)currentStep animated:(BOOL)animated;
-(void)setExtraStepProgress:(CGFloat)progress animated:(BOOL)animated;
-(void)setSuccessSubtitle:(NSString*)subtitle;
-(void)setCloseButtonTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
#end
.m file:
#import "SVProgressHudView.h"
#import <QuartzCore/QuartzCore.h>
#import <Three20/Three20.h>
#import "Three20UI/UIViewAdditions.h"
#import "Globals.h"
#import "SVGradientButton.h"
#define kMinimumWidth 100
#define kMinimumHeight 100
#define kHorizontalMargin 20
#define kVerticalMargin 20
#define kLittleVerticalMargin 7
#define kCornerRadius 10
#define kOpacity 0.85
static UIFont* regularSubtextFont;
static UIFont* successSubtextFont;
#interface SVProgressHudView(Private)
-(void)done;
#end
#implementation SVProgressHudView
#synthesize
removeFromSuperViewOnHide = _removeFromSuperViewOnHide;
+(void)initialize{
regularSubtextFont = [[UIFont systemFontOfSize:[UIFont systemFontSize]+3]retain];
successSubtextFont = [[UIFont systemFontOfSize:[UIFont systemFontSize]+3]retain];
}
- (id)initWithFrame:(CGRect)frame{
CGFloat minimumWidth = kMinimumWidth+kHorizontalMargin*2;
CGFloat minimumHeight = kMinimumHeight + kVerticalMargin*2;
//to ensure we can place it inside that frame
if(frame.size.width>=minimumWidth && frame.size.height >=minimumHeight){
self = [super initWithFrame:frame];
if (self) {
CGFloat bgWidth = frame.size.width - kHorizontalMargin*2;
bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, bgWidth, kMinimumHeight)];
bgView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:kOpacity];
bgView.clipsToBounds = YES;
bgView.center = CGPointMake(self.width/2.0, self.height/2.0);
bgView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
bgView.layer.cornerRadius = 10.0;
bgView.layer.masksToBounds = YES;
[self addSubview:bgView];
UIImage* closeImage = [UIImage imageNamed:#"xButton.png"];
_closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
_closeButton.frame = CGRectMake(0, 0, closeImage.size.width*1.5, closeImage.size.height*1.5);
[_closeButton setBackgroundImage:closeImage forState:UIControlStateNormal];
[_closeButton addTarget:self action:#selector(closeFired) forControlEvents:UIControlEventTouchUpInside];
_closeButton.right = bgView.right +_closeButton.width/3;
[self addSubview:_closeButton];
_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(kHorizontalMargin, kVerticalMargin, bgWidth-kHorizontalMargin*2, 20)];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = UITextAlignmentCenter;
_titleLabel.backgroundColor = [UIColor clearColor];
[bgView addSubview:_titleLabel];
_progress = [[PDColoredProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
_progress.delegate = self;
[_progress setBackgroundColor:[UIColor clearColor]];
[_progress setTintColor:[UIColor colorWithWhite:0.5 alpha:1.0]];//[Globals defaultTintColorForNavBar]];
[bgView addSubview:_progress];
[_progress sizeToFit];
_progress.top = _titleLabel.bottom+kVerticalMargin;
_progress.width = bgWidth-kHorizontalMargin*2-kCornerRadius*2;
_progress.left = kHorizontalMargin+kCornerRadius;
_progress.progress = 0.0;
_percentLabel = [[UILabel alloc]initWithFrame:CGRectMake(_progress.left, _progress.bottom+kLittleVerticalMargin, _progress.width/2, 20)];
_percentLabel.textColor = [UIColor whiteColor];
_percentLabel.textAlignment = UITextAlignmentLeft;
_percentLabel.backgroundColor = [UIColor clearColor];
_percentLabel.font = regularSubtextFont;
[bgView addSubview:_percentLabel];
_subtitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(_percentLabel.right, _percentLabel.top, _percentLabel.width, 20)];
_subtitleLabel.textColor = [UIColor whiteColor];
_subtitleLabel.textAlignment = UITextAlignmentRight;
_subtitleLabel.backgroundColor = [UIColor clearColor];
_subtitleLabel.font = regularSubtextFont;
[bgView addSubview:_subtitleLabel];
bgView.height = _subtitleLabel.bottom+kVerticalMargin;
bgView.center = self.center;
_closeButton.top = bgView.top - _closeButton.height/3;
_extraStep = NO;
}
}
return self;
}
-(id)initWithFrame:(CGRect)frame title:(NSString*)title numberOfSteps:(NSUInteger)numberOfSteps extraStep:(BOOL)exrta{
self = [self initWithFrame:frame];
if(self){
_titleLabel.text = title;
_numOfSteps = numberOfSteps;
_extraStep = exrta;
if(_extraStep){
CGFloat stepPart = 1.0/numberOfSteps;
_extraStepPart = stepPart/10;
_oneStepPart = (1.0-_extraStepPart)/numberOfSteps;
}else{
_oneStepPart = 1.0/numberOfSteps;
}
[self setCurrentStep:0 animated:NO];
}
return self;
}
-(void)dealloc{
TT_RELEASE_SAFELY(_titleLabel);
TT_RELEASE_SAFELY(_subtitleLabel);
TT_RELEASE_SAFELY(_percentLabel);
TT_RELEASE_SAFELY(_progress);
TT_RELEASE_SAFELY(bgView);
[super dealloc];
}
#pragma mark - Showing and Hiding
- (void)show:(BOOL)animated {
self.alpha = 0.0;
// Fade in
if (animated) {
[UIView animateWithDuration:0.3
animations:^{
self.alpha = 1.0;
}];
}else {
self.alpha = 1.0;
}
}
- (void)hide:(BOOL)animated {
if (animated) {
[UIView animateWithDuration:0.3
animations:^{
self.alpha = 0.2;
}
completion:^(BOOL finished) {
[self done];
}];
}
else {
[self done];
}
}
#pragma mark - Private Methods
- (void)done {
self.alpha = 0.0;
if (_removeFromSuperViewOnHide) {
[self removeFromSuperview];
}
}
#pragma mark - Public Methods
+ (BOOL)isThereHudAddedToView:(UIView*)view{
for (UIView *v in [view subviews]) {
if ([v isKindOfClass:[SVProgressHudView class]]) {
return YES;
}
}
return NO;
}
+ (SVProgressHudView *)hudAddedTo:(UIView *)view withTitle:(NSString*)title numberOfSteps:(NSUInteger)numberOfSteps extraStep:(BOOL)exrta{
SVProgressHudView *hud = [[SVProgressHudView alloc] initWithFrame:view.bounds title:title numberOfSteps:numberOfSteps extraStep:exrta];
hud.alpha = 0.0;
[view addSubview:hud];
return [hud autorelease];
}
-(void)setCurrentStepProgress:(CGFloat)currentStepProgress animated:(BOOL)animated{
if(currentStepProgress < 0.0){
currentStepProgress = 0.0;
}
if(currentStepProgress > 1.0){
currentStepProgress = 1.0;
}
CGFloat currentProgress = _oneStepPart*_currentStep;
currentProgress += _oneStepPart*currentStepProgress;
[_progress setProgress:currentProgress animated:animated];
}
-(void)setCurrentStep:(NSUInteger)currentStep animated:(BOOL)animated{
if(currentStep > _numOfSteps){
currentStep = _numOfSteps;
}
_currentStep = currentStep;
_subtitleLabel.text = [NSString stringWithFormat:#"%d/%d",currentStep+1,_numOfSteps];
_subtitleLabel.font = regularSubtextFont;
[self setCurrentStepProgress:0.0 animated:animated];
}
-(void)setExtraStepProgress:(CGFloat)progress animated:(BOOL)animated{
if(progress < 0.0){
progress = 0.0;
}
if(progress > 1.0){
progress = 1.0;
}
if(progress == 1.0){
//hide the close button
_closeButton.hidden = YES;
}
CGFloat currentProgress = _oneStepPart*_numOfSteps;
currentProgress += _extraStepPart*progress;
[_progress setProgress:currentProgress animated:animated];
}
-(void)progressUpdated:(PDColoredProgressView *)progressView toValue:(CGFloat)value{
_percentLabel.text = [NSString stringWithFormat:#"%d%%",(int)(value*100)];
}
-(void)setSuccessSubtitle:(NSString *)subtitle{
[_progress setProgress:1.0 animated:YES];
_subtitleLabel.text = subtitle;
_subtitleLabel.font = successSubtextFont;
}
-(void)closeFired{
[_progress cancelAnimations];
}
-(void)setCloseButtonTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{
[_closeButton addTarget:target action:action forControlEvents:controlEvents];
}
#end
It's far from being perfect as it was created for specific purpose, but it's doing the job.Hope it helps.Happy coding.
I'm using pageControl in my application. View's are not changing on click on dots but on the either end's of pageControl, when i click view's are changing. I want them to change on clicks on dot. What to do? Is there any method i need to implement?
Here's the Code
#import "ScrollingViewController.h"
#implementation ScrollingViewController
#synthesize scrollView;
#synthesize pageControl;
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupPage];
pageControl =[[UIPageControl alloc] initWithFrame:CGRectMake(0,390,320,100)];
pageControl.userInteractionEnabled =YES;
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[self.pageControl setBackgroundColor:[UIColor blackColor]];
pageControl.enabled = TRUE;
[pageControl setHighlighted:YES];
[pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pageControl];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[scrollView release];
[pageControl release];
}
- (void)dealloc
{
[super dealloc];
}
- (void)setupPage
{
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,400)];
[scrollView setContentSize:CGSizeMake(1000, 800)];
//scrollView.contentSize = CGSizeMake(1000,800);
scrollView.scrollsToTop = NO;
[self.scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
CGFloat cx = 0;
for (; ; nimages++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (image == nil)
{
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = image.size.height;
rect.size.width = image.size.width;
rect.origin.x = ((scrollView.frame.size.width - image.size.width) / 2) + cx;
rect.origin.y = ((scrollView.frame.size.height - image.size.height) / 2);
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += scrollView.frame.size.width;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
scrollView.delegate = self;
[self.view addSubview:scrollView];
}
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
if (pageControlIsChangingPage)
{
return;
}
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
pageControlIsChangingPage = NO;
}
- (IBAction)changePage:(id)sender
{
/*
* Change the scroll view
*/
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageControl.currentPage;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
pageControlIsChangingPage = YES;
}
#end
Increase the width of the page control as much as possible. Even if you keep the width of page control short enough to as many dots that it cannot hold, it can show them. But fails to receive the action.
Use in ScrollView.m
#pragma mark -
#pragma mark loadGalleryView
-(void) loadGalleryView{
galleryArr = [memberDic objectForKey:#"arrKey"];
if ([galleryArr count]%5 != 0)
{
noOfPages = ([galleryArr count]/5)+1;
}
else
{
noOfPages = [galleryArr count]/5;
}
viewControllers = [[NSMutableArray alloc] init];
for (int i=0; i<noOfPages; i++)
{
[viewControllers addObject:[NSNull null]];
}
[galleryScrollView setPagingEnabled:TRUE];
[galleryScrollView setContentSize:CGSizeMake(self.view.frame.size.width* noOfPages,69.0f)];
[galleryScrollView setShowsHorizontalScrollIndicator:FALSE];
[galleryScrollView setShowsVerticalScrollIndicator:FALSE];
[galleryScrollView setScrollsToTop:FALSE];
[galleryScrollView setDelegate:self];
[pageControl setNumberOfPages:noOfPages];
[pageControl setCurrentPage:0];
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
//-----------------Load scroll View----------------------------------
-(void) loadScrollViewWithPage:(int) page{
if (page < 0)
{
return;
}
if (page >= noOfPages)
{
return;
}
GalleryViewController *givc = [viewControllers objectAtIndex:page];
if ((NSNull *)givc == [NSNull null])
{
givc = [[GalleryViewController alloc] initWithPageNumber:page];
givc.imageArr = [galleryArr retain];
[viewControllers replaceObjectAtIndex:page withObject:givc];
[givc release];
}
if (nil == givc.view.superview)
{
CGRect frame = self.view.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
givc.view.frame = frame;
[galleryScrollView addSubview:givc.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = galleryScrollView.frame.size.width;
int page = floor((galleryScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
isPageControlUsed = NO;
}
Use in GalleryView .m
- (void)viewDidLoad {
[super viewDidLoad];
float x = 7.0f;
for (int i = (pageNumber*5); i<(pageNumber+1)*5; i++)
{
if (i<[imageArr count])
{
NSString *url = [imageArr objectAtIndex:i];
MyImageView *imgView = [[MyImageView alloc] initWithFrame:CGRectMake(x, 7.5f, 55.0f, 55.0f)];
[imgView addImageFrom:url];
[self.view addSubview:imgView];
[imgView release];
x = x+62.5f;
}
}
}
-(id)initWithPageNumber:(int) page{
if (self = [super initWithNibName:#"GalleryViewController" bundle:nil])
{
pageNumber = page;
}
return self;
}
I have text on label which is not appearing completely so i want text to scroll on label from left to right. Please don't suggest numberoflines property as a solution.
FWIW, I did something similar using 2 labels in a scroll view...
#import <UIKit/UIKit.h>
#interface ScrolledTextView : UIScrollView
{
UILabel *label1;
UILabel *label2;
NSString *_text;
NSString *newText;
CGFloat textWidth;
BOOL animating;
BOOL needToUpdateText;
}
#property (nonatomic, copy, setter = setText:) NSString *text;
#property (nonatomic, assign) NSTimeInterval scrollInterval;
#property (nonatomic, assign) NSTimeInterval scrollDuration;
- (id) initWithFrame:(CGRect)frame andText : (NSString*) text;
- (void) setText:(NSString *)text;
- (BOOL) textFitsInFrame;
#implementation ScrolledTextView
#synthesize text = _text;
#synthesize scrollDuration;
#synthesize scrollInterval;
- (void) adjustLabelsForNewText : (NSString*) text andParentFrame : (CGRect) frame
{
_text = [NSString stringWithFormat:#"%# ", text];
CGSize textSize = [[self text] sizeWithFont:[label1 font] constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) lineBreakMode:UILineBreakModeClip];
[self setContentSize:CGSizeMake(textSize.width * 2, textSize.height)];
textWidth = textSize.width;
[label1 setFrame:CGRectMake(0.0, 0.0, textWidth, frame.size.height)];
[label1 setText:[self text]];
if([self textFitsInFrame])
{
[label2 removeFromSuperview];
}
else
{
[label2 setFrame:CGRectMake([label1 frame].size.width, 0.0, textWidth, frame.size.height)];
[label2 setText:[self text]];
if( ! [[self subviews] containsObject:label2])
{
[self addSubview:label2];
}
[self beginScrolling];
}
}
- (id) initWithFrame:(CGRect)frame andText : (NSString*) text
{
self = [super initWithFrame:frame];
if (self) {
[self setClipsToBounds:YES];
animating = NO;
needToUpdateText = NO;
[self setScrollDuration:10.0];
[self setScrollInterval:2.0];
label1 = [UILabel new];
label2 = [UILabel new];
[label1 setBackgroundColor:[UIColor clearColor]];
[label2 setBackgroundColor:[UIColor clearColor]];
[self addSubview:label1];
[self adjustLabelsForNewText:text andParentFrame:frame];
}
return self;
}
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if(needToUpdateText)
{
animating = NO;
needToUpdateText = NO;
[self adjustLabelsForNewText:#"" andParentFrame:[self frame]];
[self adjustLabelsForNewText:newText andParentFrame:[self frame]];
newText = nil;
return;
}
[self setContentOffset:CGPointMake(0.0, 0.0)];
[self beginScrolling];
}
- (void) beginScrolling
{
animating = YES;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:[self scrollDuration]];
[UIView setAnimationDelay:[self scrollInterval]];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[self setContentOffset:CGPointMake(textWidth, 0.0)];
[UIView commitAnimations];
}
- (BOOL) textFitsInFrame
{
return textWidth <= [self frame].size.width;
}
- (void) setText:(NSString *)text
{
if(animating)
{
newText = text;
needToUpdateText = YES;
}
else
{
[self adjustLabelsForNewText:text andParentFrame:[self frame]];
}
}
if u appear a complete string in label using this line
CGSize labelsize = [label.text sizeWithFont:label.font];
then in CGRectMark(10,10, label.width,100 );
marquee are based on scroll content-size,if u set content-size(200,300),mean take that value to compare with x and y value to set a marquee.
regard
CNSivakumar
I have some strange behavior using a UIPageControl:
First it appears showing only one bullet, then when I move the scroll view all the bullets appear correctly. Is there something I'm missing before I add it as a subview?
Here is my code imageScrollView.h :
#interface ImageScrollView : UIView <UIScrollViewDelegate> {
NSMutableDictionary *photos;
BOOL *pageControlIsChangingPage;
UIPageControl *pageControl;
}
#property (nonatomic, copy) NSMutableDictionary *photos;
#property (nonatomic, copy) UIPageControl *pageControl;
#end
Here is the code for imageScrollView.m:
#import "ImageScrollView.h"
#implementation ImageScrollView
#synthesize photos, pageControl;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
}
return self;
}
- (void) drawRect:(CGRect)rect
{
[self removeAllSubviews];
UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];
[scroller setDelegate:self];
[scroller setBackgroundColor:[UIColor grayColor]];
[scroller setShowsHorizontalScrollIndicator:NO];
[scroller setPagingEnabled:YES];
NSUInteger nimages = 0;
CGFloat cx= 0;
for (NSDictionary *myDictionaryObject in photos)
{
if (![myDictionaryObject isKindOfClass:[NSNull class]]) {
NSString *photo =[NSString stringWithFormat:#"http://www.techbase.com.mx/blog/%#",[myDictionaryObject objectForKey:#"filepath"]];
NSDictionary *data = [myDictionaryObject objectForKey:#"data"];
UIView *imageContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 30)];
TTImageView *imageView = [[TTImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 30)];
imageView.urlPath=photo;
[imageContainer addSubview:imageView];
UILabel *caption = [[UILabel alloc] initWithFrame:CGRectMake(0,imageView.frame.size.height,imageView.frame.size.width,10)];
[caption setText:[NSString stringWithFormat:#"%#",[data objectForKey:#"description"]]];
[caption setBackgroundColor:[UIColor grayColor]];
[caption setTextColor:[UIColor whiteColor]];
[caption setLineBreakMode:UILineBreakModeWordWrap];
[caption setNumberOfLines:0];
[caption sizeToFit];
[caption setFont:[UIFont fontWithName:#"Georgia" size:10.0]];
[imageContainer addSubview:caption];
CGRect rect = imageContainer.frame;
rect.size.height = imageContainer.size.height;
rect.size.width = imageContainer.size.width;
rect.origin.x = ((scroller.frame.size.width - scroller.size.width) / 2) + cx;
rect.origin.y = ((scroller.frame.size.height - scroller.size.height) / 2);
imageContainer.frame=rect;
[scroller addSubview:imageContainer];
[imageView release];
[imageContainer release];
[caption release];
nimages++;
cx +=scroller.frame.size.width;
}
}
[scroller setContentSize:CGSizeMake(nimages * self.frame.size.width, self.frame.size.height)];
[self addSubview:scroller];
pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.frame.size.width/2, self.frame.size.height -20, (self.frame.size.width/nimages)/2, 20)];
pageControl.numberOfPages=nimages;
[self addSubview:pageControl];
[scroller release];
}
-(void)dealloc {
[pageControl release];
[super dealloc];
}
-(void)scrollViewDidScroll:(UIScrollView *)_scrollView{
if(pageControlIsChangingPage){
return;
}
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth /2) / pageWidth) + 1;
pageControl.currentPage = page;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView{
pageControlIsChangingPage = NO;
}
#end
Since you're drawing the UIPageControl in the drawRect method, you need to call the setNeedsLayout method of this control after you initialize it. Otherwise it won't render itself properly until an event that forces this redrawing is called.
pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.frame.size.width/2, self.frame.size.height -20, (self.frame.size.width/nimages)/2, 20)];
pageControl.numberOfPages=nimages;
[pageControl setNeedsLayout];
[self addSubview:pageControl];