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.
Related
At first, sorry for my bad English, I'm just learning it. Im relatively new at Objective-C and I'm using FBConnect bundle to link my app to Facebook. All it's working correctly, but when I click a link into the UIWebView (the Facebook login button, for example), my UIWebView gets fullscreen and hides my close button (a little 'x' button in the top right of the UIWebView, called here "_closeButton").
Here's the code:
The "init" method:
- (id)init {
if ((self = [super initWithFrame:CGRectZero])) {
_delegate = nil;
_loadingURL = nil;
_showingKeyboard = NO;
self.backgroundColor = [UIColor clearColor];
self.autoresizesSubviews = NO;
//self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.contentMode = UIViewContentModeRedraw;
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(kPadding, kPadding, 480, 480)];
_webView.delegate = self;
//_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_webView];
//UIImage* closeImage = [UIImage imageNamed:#"FBDialog.bundle/images/close.png"];
UIImage* closeImage = [UIImage imageNamed:#"close"];
UIColor* color = [UIColor colorWithRed:255.0/255 green:/*184.0*/0.0/255 blue:/*216.0*/0.0/255 alpha:1];
_closeButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
[_closeButton setImage:closeImage forState:UIControlStateNormal];
[_closeButton setTitleColor:color forState:UIControlStateNormal];
[_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[_closeButton addTarget:self action:#selector(cancel)
forControlEvents:UIControlEventTouchUpInside];
// To be compatible with OS 2.x
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_2_2
_closeButton.font = [UIFont boldSystemFontOfSize:12];
#else
_closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
#endif
_closeButton.showsTouchWhenHighlighted = YES;
_closeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:_closeButton];
NSLog(#"close");
_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
_spinner.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self addSubview:_spinner];
_modalBackgroundView = [[UIView alloc] init];
}
return self;
}
The delegate of the WebView (I suspect here's where I need to do the trick)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = request.URL;
if ([url.scheme isEqualToString:#"fbconnect"]) {
if ([[url.resourceSpecifier substringToIndex:8] isEqualToString:#"//cancel"]) {
NSString * errorCode = [self getStringFromUrl:[url absoluteString] needle:#"error_code="];
NSString * errorStr = [self getStringFromUrl:[url absoluteString] needle:#"error_msg="];
if (errorCode) {
NSDictionary * errorData = [NSDictionary dictionaryWithObject:errorStr forKey:#"error_msg"];
NSError * error = [NSError errorWithDomain:#"facebookErrDomain"
code:[errorCode intValue]
userInfo:errorData];
[self dismissWithError:error animated:YES];
} else {
[self dialogDidCancel:url];
}
} else {
[self dialogDidSucceed:url];
}
return NO;
} else if ([_loadingURL isEqual:url]) {
return YES;
} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([_delegate respondsToSelector:#selector(dialog:shouldOpenURLInExternalBrowser:)]) {
if (![_delegate dialog:self shouldOpenURLInExternalBrowser:url]) {
return NO;
}
}
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
} else {
return YES;
}
}
And the show method (called when I need to show the Web View)
- (void)show {
NSLog(#"Cuantas veces me ves?");
[self load];
[self sizeToFitOrientation:NO];
CGFloat innerWidth = self.frame.size.width - (kBorderWidth+1)*2;
[_closeButton sizeToFit];
_closeButton.frame = CGRectMake(
2,
2,
29,
29);
_webView.frame = CGRectMake(
kBorderWidth+1,
kBorderWidth+1,
innerWidth,
self.frame.size.height - (1 + kBorderWidth*2));
[_spinner sizeToFit];
[_spinner startAnimating];
_spinner.center = _webView.center;
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
_modalBackgroundView.frame = window.frame;
[_modalBackgroundView addSubview:self];
[window addSubview:_modalBackgroundView];
[window addSubview:self];
[self dialogWillAppear];
self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/1.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(bounce1AnimationStopped)];
self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
[UIView commitAnimations];
[self addObservers];
}
Googling the problem, I found that this could be the Default behaviour of the UIWebView. How can I change it to make all my WebViews of the same size than the first one?
Thanks in advance!
== EDIT ==
Still don't know why is my UIWebView acting like this, or how to solve it, but since the code is part of the FBConnect Bundle, I suppose I shouldn't edit it too much. I just created programmatically a new close button on the top and that's all. But I'll let the question open if someone knows how to solve it. Thanks to Leo Natan for his help.
I am newbie trying to make an app similar to Notes app of iPhone using UITextView.
I am getting the textView and lines and it is working fine.
My problem is that I want to add a UINavigationBar and back button on it.
And I want to add a UIToolBar at the bottom and 2 toolBarItems on it how to do this programmetically. Any help will be a great push up for me..
below is the code snippet.
NoteView.h
#interface NoteView : UITextView <UITextViewDelegate,UITabBarControllerDelegate>
{
}
NoteView.m
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithRed:0.6f green:0.6f blue:1.0f alpha:1.0f];
self.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:20];
self.contentMode = UIViewContentModeRedraw;
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.2f].CGColor);
CGContextSetLineWidth(context, 1.0f);
CGContextBeginPath(context);
NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading;
CGFloat baselineOffset = 6.0f;
for (int x = 0; x < numberOfLines; x++) {
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);
}
CGContextClosePath(context);
CGContextStrokePath(context);
}
AddNotesViewController.h
#interface AddNotesViewController : UIViewController <UITextViewDelegate,UITabBarDelegate>
{
NoteView *note;
}
#property (nonatomic, retain) NoteView *note;
#end
AddNotesViewController.m
- (void)loadView
{
[super loadView];
self.note = [[[NoteView alloc] initWithFrame:self.view.bounds] autorelease];
[self.view addSubview:note];
note.delegate = self;
note.text=#"";
}
- (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;
}
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
if ([text isEqualToString:#"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
Please tell me how and where to add navigation bar , back button and tool bar ,2 toolBarItems on it.Thanks in advance...
Navigation Bar Image
UINavigationBar *navBar = [[self navigationController] navigationBar];
UIImage *image = [UIImage imageNamed:#"TopBar.png"];
[navBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
Back Button
-(void)getBackBtn
{
UIButton *Btn =[UIButton buttonWithType:UIButtonTypeCustom];
[Btn setFrame:CGRectMake(0.0f,0.0f,50.0f,30.0f)];
[Btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:#"back.png"]] forState:UIControlStateNormal];
//[Btn setTitle:#"OK" forState:UIControlStateNormal];
//Btn.titleLabel.font = [UIFont fontWithName:#"Georgia" size:14];
[Btn addTarget:self action:#selector(backBtnPress:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:Btn];
[self.navigationItem setLeftBarButtonItem:addButton];
}
BackButtonAction
-(IBAction)backBtnPress:(id)sender
{
}
View on NavigationBar
For View on navigationBar you can follow my answer Link
use this code....
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithTitle:NSLocalizedString(#"Back", #"")
style:UIBarButtonItemStyleDone
target:self
action:#selector(YourActionMethod:)];
self.navigationItem.leftBarButtonItem = addButton;
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 am trying to make a survey app but I can't make the memory management although I am using ARC. My app makes memory leak. I get memory warning. When I make my app in interface builder statically there is no problem but when i make my app programmatically I get memory problem. Why is that happening? Here is my code:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
int soruAdedi = 20;
#interface ViewController ()
#end
#implementation ViewController
#synthesize scrollView2;
-(void)textViewBicimle: (UITextField *)textAlani{
[textAlani.layer setBorderColor:[[[UIColor blackColor] colorWithAlphaComponent:1.0] CGColor]];
[textAlani.layer setBorderWidth:1.0];
}
- (void) tableCiz:(NSMutableArray *)hucreler sutun:(int)sutunSayisi satir:(int)satirSayisi{
int z = 0;
for (int i =0;i<satirSayisi;i++){
for(int j=0;j<sutunSayisi&&z<satirSayisi*sutunSayisi;j++,z++){
[self textViewBicimle:[hucreler objectAtIndex:z]];
[[hucreler objectAtIndex:z] setFrame:CGRectMake((20+j*100), (20+i*40), 100, 40)];
}
}
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
}
-(void)hucreArrayOlustur: (int)sutunSayisi suankiView:(UIView *)soruViewIki satir:(int)satirSayisi{
for (int i = 0; i <sutunSayisi*satirSayisi; i++){
textView = [[UITextField alloc]init];
textView.text = #"dsgfdh";
[hucreArray addObject:textView];
[soruViewIki addSubview:textView];
}
}
-(void)viewOlustur{
for (int i = 0; i <soruAdedi; i++){
hucreArray = [[NSMutableArray alloc]init];
if (i == 0){
soruView = [[UIView alloc]initWithFrame:CGRectMake(20, 20, 728, 0)];
soruView.clipsToBounds = YES;
soruView.backgroundColor = [UIColor lightGrayColor];
[self hucreArrayOlustur:5 suankiView:soruView satir:10];
[self tableCiz:hucreArray sutun:5 satir:10];
CGRect frame = soruView.frame;
CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
frame.size.height = frame2.origin.y+frame2.size.height+34;
soruView.frame = frame;
[viewArray addObject:soruView];
[scrollView2 addSubview:soruView];
}
else{
CGRect frameGecici = [[viewArray objectAtIndex:i-1] frame];
float geciciY = frameGecici.origin.y+frameGecici.size.height+1;
soruView = [[UIView alloc]initWithFrame:CGRectMake(20, geciciY, 728, 0)];
soruView.clipsToBounds = YES;
soruView.backgroundColor = [UIColor lightGrayColor];
[self hucreArrayOlustur:5 suankiView:soruView satir:10];
[self tableCiz:hucreArray sutun:5 satir:10];
CGRect frame = soruView.frame;
CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
frame.size.height = frame2.origin.y+frame2.size.height+34;
soruView.frame = frame;
[viewArray addObject:soruView];
[scrollView2 addSubview:soruView];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
scrollView2.delegate = self;
scrollView2.contentSize = CGSizeMake(0, 8000);
viewArray = [[NSMutableArray alloc]init];
[self viewOlustur];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setScrollView2:nil];
[super viewDidUnload];
}
#end
I have a class that implements "UIView" and inside - (void)drawRect:(CGRect)rect method I add some custom buttons to self. Inside a UIViewController I declare an instance of this view and i add it to self.view.
If i do this in - (void)viewDidLoad, everything works perfect, but if I create a method that is called when I push a button, and add that view to self.view, the buttons background is displayed after a few second. Till then only the name of the button appears written in white.
What do i do wrong?
Regards
#implementation CustomButton
#synthesize isPressed, buttonViewNumber;
- (id)initWithFrame:(CGRect)frame
title:(NSString *)title
tag:(int)tag
{
self = [super initWithFrame:frame];
if (self) {
[self setTitle:title forState:UIControlStateNormal];
[self setTag:tag];
self.titleLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self setBackgroundImage:[[UIImage imageNamed:#"btn_white_add.png"] stretchableImageWithLeftCapWidth:20.0 topCapHeight:0.0] forState:UIControlStateNormal];
[self addTarget:self action:#selector(didSelect) forControlEvents:UIControlEventTouchUpInside];
self.isPressed = NO;
}
return self;
}
#implementation ButtonsView
#synthesize listOfButtons;
- (id)initWithFrame:(CGRect)frame bundle:(NSArray *)data
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
listOfNames = [[NSArray arrayWithArray:data] retain];
listOfButtons = [[NSMutableArray alloc] init];
currentViewNumber = 0;
viewNumber = 0;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGSize maximumLabelSize = CGSizeMake(300,24);
UIFont *buttonFont = [UIFont fontWithName:#"Helvetica" size:14.0];
float lineSize = 0;
float lineNumber = 0;
NSArray *listOfFrameX = [NSArray arrayWithObjects:
[NSString stringWithFormat:#"%d",FIRST_LINE_Y],
[NSString stringWithFormat:#"%d",SECOND_LINE_Y],
[NSString stringWithFormat:#"%d",THIRD_LINE_Y],
nil];
for (int i = 0; i < [listOfNames count]; i++) {
CGSize expectedLabelSize = [[[listOfNames objectAtIndex:i] objectForKey:#"name"] sizeWithFont:buttonFont
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeTailTruncation];
if ((lineSize + expectedLabelSize.width) > 260) {
lineNumber++;
lineSize = 0;
}
if (lineNumber > 2) {
viewNumber ++;
lineSize = 0;
lineNumber = 0;
}
CGRect newFrame = CGRectMake(lineSize,
[[listOfFrameX objectAtIndex:lineNumber] floatValue],
expectedLabelSize.width+30,
24);
CustomButton *myButton = [[CustomButton alloc] initWithFrame:newFrame
title:[[listOfNames objectAtIndex:i] objectForKey:#"name"]
tag:[[[listOfNames objectAtIndex:i] objectForKey:#"id"] intValue]];
myButton.buttonViewNumber = viewNumber;
[listOfButtons addObject:myButton];
if (viewNumber == 0) {
[self addSubview:myButton];
}
lineSize += expectedLabelSize.width + 40;
[myButton release];
}
}
this way it works:
- (void)viewDidLoad
{
[super viewDidLoad];
placeholders = [[NSArray arrayWithObjects:
something,something, something,something,nil] retain];
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:placeholders];
[self.view addSubview:buttonsView];
and like this is doesnt work:
- (void)getCompanyNames:(id)result
{
NSArray *listOfCompanies = (NSArray *)result;
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:listOfCompanies];
[self.view addSubview:buttonsView];
}
i need to add the "buttonsView" object to self.view after the -viewDidLoad
drawRect: isn't exactly the place you should be creating subviews (Buttons are subviews) for your view. This should either go into initWithFrame: or awakeFromNib, depending on your view creation method: programmatically or using a nib.