Application run on simulator but not on device in iphone - iphone

I am using SlideView Controller and mainly when application enter through dropbox(login with dropbox) it goes to FirstViewController and in Simulator whole app is working correctly but in device when it enter to FirstViewController it crash even it show its interface.
in FirstViewController,it linked with slideViewController and slideViewController have property of tableview and slideview so that next controller(slideViewController) is appear..
I have some code for slideViewController. Even in FirstViewController, application is goes under viewdidload and then slideViewController but i have tried lot of but in device application got crash.
Can anyone help me to get me out of this issue
i am posting my code below..
#import "SlideViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "CustomViewController.h"
#import "ClassViewController.h"
#import "AssignmentViewController.h"
#import "SectionViewController.h"
#import "SlideViewControllerTableCell.h"
#import "LogoutCell.h"
#import "MainViewController.h"
#import <DropboxSDK/DropboxSDK.h>
#define kSVCLeftAnchorX 100.0f
#define kSVCRightAnchorX 190.0f
#define kSVCSwipeNavigationBarOnly NO
#interface SlideViewNavigationBar : UINavigationBar {
#private
id <SlideViewNavigationBarDelegate> _slideViewNavigationBarDelegate;
}
#property (nonatomic, assign) id <SlideViewNavigationBarDelegate> slideViewNavigationBarDelegate;
#end
#implementation SlideViewNavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:#"class button1.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width+10, self.frame.size.height+10)];
UIImage *image1 = [UIImage imageNamed:#"skirrwhite.png"];
[image1 drawInRect:CGRectMake(40, 10,80, 26)];
}
#end
#implementation SlideViewNavigationBar
#synthesize slideViewNavigationBarDelegate = _slideViewNavigationBarDelegate;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self.slideViewNavigationBarDelegate slideViewNavigationBar:self touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self.slideViewNavigationBarDelegate slideViewNavigationBar:self touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self.slideViewNavigationBarDelegate slideViewNavigationBar:self touchesEnded:touches withEvent:event];
}
#end
#implementation SlideViewController
#synthesize delegate = _delegate;
#synthesize calert;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:#"SlideViewController" bundle:nil];
if (self) {
_touchView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
_touchView.exclusiveTouch = NO;
_overlayView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 44.0f, 320.0f, 416.0f)];
_slideNavigationControllerState = kSlideNavigationControllerStateNormal;
}
return self;
}
- (void)dealloc {
[_touchView release];
[_overlayView release];
[_slideNavigationController release];
[super dealloc];
}
#pragma mark - View Lifecycle
- (void)viewDidLoad {
if (![self.delegate respondsToSelector:#selector(configureSearchDatasourceWithString:)] || ![self.delegate respondsToSelector:#selector(searchDatasource)]) {
_searchBar.hidden = YES;
_tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, 460.0f);
}
_slideNavigationController.view.layer.shadowColor = [[UIColor blackColor] CGColor];
_slideNavigationController.view.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
_slideNavigationController.view.layer.shadowRadius = 4.0f;
_slideNavigationController.view.layer.shadowOpacity = 0.75f;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:_slideNavigationController.view.bounds cornerRadius:4.0];
_slideNavigationController.view.layer.shadowPath = path.CGPath;
[(SlideViewNavigationBar *)_slideNavigationController.navigationBar setSlideViewNavigationBarDelegate:self];
UIImage *searchBarBackground = [UIImage imageNamed:#"search_bar_background"];
[_searchBar setBackgroundImage:[searchBarBackground stretchableImageWithLeftCapWidth:0 topCapHeight:0]];
UIViewController *initalViewController = [self.delegate initialViewController];
[self configureViewController:initalViewController];
[_slideNavigationController setViewControllers:[NSArray arrayWithObject:initalViewController] animated:NO];
[self addChildViewController:_slideNavigationController];
[self.view addSubview:_slideNavigationController.view];
if ([self.delegate respondsToSelector:#selector(initialSelectedIndexPath)])
[_tableView selectRowAtIndexPath:[self.delegate initialSelectedIndexPath] animated:NO scrollPosition:UITableViewScrollPositionTop];
}
#pragma mark Instance Methods
- (void)configureViewController:(UIViewController *)viewController {
UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
[tempButton setFrame:CGRectMake(1, 1, 14, 30)]; // your Home Button Image width and height.
[tempButton addTarget:self action:#selector(menuBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
[tempButton setImage:[UIImage imageNamed:#"ic_drawer.png"] forState:UIControlStateNormal];
//[tempButton setImage:[UIImage imageNamed:#"twitterIcon.png"] forState:UIControlStateHighlighted];
[viewController.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:tempButton]];
}
- (void)menuBarButtonItemPressed:(id)sender {
if (_slideNavigationControllerState == kSlideNavigationControllerStatePeeking) {
[self slideInSlideNavigationControllerView];
return;
}
UIViewController *currentViewController = [[_slideNavigationController viewControllers] objectAtIndex:0];
if ([currentViewController conformsToProtocol:#protocol(SlideViewControllerSlideDelegate)] && [currentViewController respondsToSelector:#selector(shouldSlideOut)]) {
if ([(id <SlideViewControllerSlideDelegate>)currentViewController shouldSlideOut]) {
[self slideOutSlideNavigationControllerView];
}
} else {
[self slideOutSlideNavigationControllerView];
}
}
- (void)slideOutSlideNavigationControllerView {
_slideNavigationControllerState = kSlideNavigationControllerStatePeeking;
[UIView animateWithDuration:0.2 delay:0.0f options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState animations:^{
_slideNavigationController.view.transform = CGAffineTransformMakeTranslation(260.0f, 0.0f);
} completion:^(BOOL finished) {
[_slideNavigationController.view addSubview:_overlayView];
}];
}
- (void)slideInSlideNavigationControllerView {
[UIView animateWithDuration:0.2 delay:0.0f options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState animations:^{
_slideNavigationController.view.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
[self cancelSearching];
_slideNavigationControllerState = kSlideNavigationControllerStateNormal;
[_overlayView removeFromSuperview];
}];
}
- (void)slideSlideNavigationControllerViewOffScreen {
_slideNavigationControllerState = kSlideNavigationControllerStateSearching;
[UIView animateWithDuration:0.2 delay:0.0f options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState animations:^{
_slideNavigationController.view.transform = CGAffineTransformMakeTranslation(320.0f, 480.0f);
} completion:^(BOOL finished) {
[_slideNavigationController.view addSubview:_overlayView];
}];
}
#pragma mark UITouch Logic
- (void)cancelSearching {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
[_searchBar resignFirstResponder];
_slideNavigationControllerState = kSlideNavigationControllerStateNormal;
_searchBar.text = #"";
[_tableView reloadData];
}
}
#pragma mark SlideViewNavigationBarDelegate Methods
- (void)slideViewNavigationBar:(SlideViewNavigationBar *)navigationBar touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}
- (void)slideViewNavigationBar:(SlideViewNavigationBar *)navigationBar touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesMoved:touches withEvent:event];
}
- (void)slideViewNavigationBar:(SlideViewNavigationBar *)navigationBar touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesEnded:touches withEvent:event];
}
#pragma mark UINavigationControlerDelgate Methods
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
[self cancelSearching];
if ([[navigationController viewControllers] count] > 1) {
_slideNavigationControllerState = kSlideNavigationControllerStateDrilledDown;
} else {
_slideNavigationControllerState = kSlideNavigationControllerStateNormal;
}
}
#pragma mark UITableViewDelegate / UITableViewDatasource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
return [[self.delegate searchDatasource] count];
} else {
return [[[[self.delegate datasource] objectAtIndex:section] objectForKey:kSlideViewControllerSectionViewControllersKey] count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
return 1;
} else {
return [[self.delegate datasource] count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *resuseIdentifier = #"SlideViewControllerTableCell";
SlideViewControllerTableCell *cell = [tableView dequeueReusableCellWithIdentifier:resuseIdentifier];
if (!cell) {
cell = [[[SlideViewControllerTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resuseIdentifier] autorelease];
}
NSDictionary *viewControllerDictionary = nil;
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
viewControllerDictionary = [[self.delegate searchDatasource] objectAtIndex:indexPath.row];
} else {
viewControllerDictionary = [[[[self.delegate datasource] objectAtIndex:indexPath.section] objectForKey:kSlideViewControllerSectionViewControllersKey] objectAtIndex:indexPath.row];
}
cell.textLabel.text = [viewControllerDictionary objectForKey:kSlideViewControllerViewControllerTitleKey];
if ([[viewControllerDictionary objectForKey:kSlideViewControllerViewControllerIconKey] isKindOfClass:[UIImage class]]) {
cell.imageView.image = [viewControllerDictionary objectForKey:kSlideViewControllerViewControllerIconKey];
//cell.imageView.image =[[]]
} else {
cell.imageView.image = nil;
}
UIView *v = [[[UIView alloc] init] autorelease];
v.backgroundColor = [UIColor redColor];
[cell setBackgroundColor:[UIColor clearColor]];
cell.textLabel.textColor = [UIColor colorWithRed:190.0f/255.0f green:197.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.textLabel.textColor = [UIColor colorWithRed:190.0f/255.0f green:197.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
//cell.textLabel.highlightedTextColor = self.textLabel.textColor;
cell.textLabel.shadowColor = [UIColor colorWithRed:33.0f/255.0f green:38.0f/255.0f blue:49.0f/255.0f alpha:1.0f];
cell.textLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:12.0f];
cell.imageView.clipsToBounds = YES;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
NSString *strTemp = [NSString stringWithFormat:#"%#",[viewControllerDictionary objectForKey:kSlideViewControllerViewControllerTitleKey]];
// float height = [strTemp boundingRectWithSize:(CGSize)13.0 options:nil attributes:nil context:nil];
float height = [strTemp sizeWithFont:[UIFont fontWithName:#"Helvetica" size:13.0] constrainedToSize:CGSizeMake(300, 30) lineBreakMode:NSLineBreakByWordWrapping].height;
[cell.textLabel setNumberOfLines:0];
[cell.textLabel setText:strTemp];
[cell.textLabel setFrame:CGRectMake(0, 0, 160, height)];
return cell;
}
-(IBAction)logout:(id)sender
{
[[DBSession sharedSession] unlinkAll];
MainViewController *fc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[self.navigationController pushViewController:fc animated:YES];
[fc release];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching)
return nil;
NSDictionary *sectionDictionary = [[self.delegate datasource] objectAtIndex:section];
if ([sectionDictionary objectForKey:kSlideViewControllerSectionTitleKey]) {
NSString *sectionTitle = [sectionDictionary objectForKey:kSlideViewControllerSectionTitleKey];
if ([sectionTitle isEqualToString:kSlideViewControllerSectionTitleNoTitle]) {
return nil;
} else {
return sectionTitle;
}
} else {
return nil;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching)
return nil;
NSString *titleString = [self tableView:tableView titleForHeaderInSection:section];
if (!titleString)
return nil;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 22.0f)];
imageView.image = [[UIImage imageNamed:#"section_background"] stretchableImageWithLeftCapWidth:0.0f topCapHeight:0.0f];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectInset(imageView.frame, 10.0f, 0.0f)];
titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:12.0f];
titleLabel.textAlignment = UITextAlignmentLeft;
titleLabel.textColor = [UIColor colorWithRed:125.0f/255.0f green:129.0f/255.0f blue:146.0f/255.0f alpha:1.0f];
titleLabel.shadowColor = [UIColor colorWithRed:40.0f/255.0f green:45.0f/255.0f blue:57.0f/255.0f alpha:1.0f];
titleLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.text = titleString;
[imageView addSubview:titleLabel];
[titleLabel release];
return [imageView autorelease];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
return 0.0f;
}
else if ([self tableView:tableView titleForHeaderInSection:section]) {
return 22.0f;
} else {
return 0.0f;
}
}
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
if (section == 4) {
return 40.0;
}
else {
return 10.0;
}
}
-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
if(section == 4)
{
UIButton *logoutImage = [UIButton buttonWithType:UIButtonTypeCustom];
[logoutImage setFrame:CGRectMake(35, 15, 150, 100)];
[logoutImage setImage:[UIImage imageNamed:#"logoutbutton.PNG"] forState:UIControlStateNormal];
[logoutImage addTarget:self action:#selector(logout:) forControlEvents:UIControlEventTouchUpInside];
return [logoutImage autorelease];
}
else
{
return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
//return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"indexPath ==%d",indexPath.section);
NSDictionary *viewControllerDictionary = nil;
if (_slideNavigationControllerState == kSlideNavigationControllerStateSearching) {
viewControllerDictionary = [[self.delegate searchDatasource] objectAtIndex:indexPath.row];
} else {
viewControllerDictionary = [[[[self.delegate datasource] objectAtIndex:indexPath.section] objectForKey:kSlideViewControllerSectionViewControllersKey] objectAtIndex:indexPath.row];
}
Class viewControllerClass = [viewControllerDictionary objectForKey:kSlideViewControllerViewControllerClassKey];
NSString *nibNameOrNil = [viewControllerDictionary objectForKey:kSlideViewControllerViewControllerNibNameKey];
UIViewController *viewController = [[viewControllerClass alloc] initWithNibName:nibNameOrNil bundle:nil];
if ([self.delegate respondsToSelector:#selector(configureViewController:userInfo:)])
[self.delegate configureViewController:viewController userInfo:[viewControllerDictionary objectForKey:kSlideViewControllerViewControllerUserInfoKey]];
[self configureViewController:viewController];
[_slideNavigationController setViewControllers:[NSArray arrayWithObject:viewController] animated:NO];
[viewController release];
[self slideInSlideNavigationControllerView ];
if(indexPath.section == 4)
{
if (indexPath.row == 0){
[[DBSession sharedSession] unlinkAll];
MainViewController *fc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[self.navigationController pushViewController:fc animated:YES];
[fc release];
}
}
}
#pragma mark UISearchBarDelegate Methods
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
if ([self.delegate respondsToSelector:#selector(configureSearchDatasourceWithString:)]) {
[self slideSlideNavigationControllerViewOffScreen];
[self.delegate configureSearchDatasourceWithString:searchBar.text];
[_tableView reloadData];
}
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([self.delegate respondsToSelector:#selector(configureSearchDatasourceWithString:)]) {
[self.delegate configureSearchDatasourceWithString:searchBar.text];
[_tableView reloadData];
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[self cancelSearching];
[self slideOutSlideNavigationControllerView];
[_tableView reloadData];
}
#end
ind the log says that:
2013-12-27 18:12:04.989 Skirr[1534:a0b] Application windows are expected to have a root view controller at the end of application launch
2013-12-27 18:12:45.918 Skirr[1534:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(
0 CoreFoundation 0x032745e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x021b88b6 objc_exception_throw + 44
2 CoreFoundation 0x03228316 -[__NSPlaceholderArray initWithObjects:count:] + 390
3 CoreFoundation 0x0324bce9 +[NSArray arrayWithObject:] + 73
4 Skirr 0x0000943d -[SlideViewController viewDidLoad] + 1597
5 UIKit 0x00e2d318 -[UIViewController loadViewIfRequired] + 696
6 UIKit 0x00e2d5b4 -[UIViewController view] + 35
7 UIKit 0x00e473e2 -[UINavigationController _startCustomTransition:] + 778
8 UIKit 0x00e540c7 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688
9 UIKit 0x00e54cb9 -[UINavigationController __viewWillLayoutSubviews] + 57
10 UIKit 0x00f8e181 -[UILayoutContainerView layoutSubviews] + 213
11 UIKit 0x00d84267 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
12 libobjc.A.dylib 0x021ca81f -[NSObject performSelector:withObject:] + 70
13 QuartzCore 0x005622ea -[CALayer layoutSublayers] + 148
14 QuartzCore 0x005560d4 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
15 QuartzCore 0x00555f40 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
16 QuartzCore 0x004bdae6 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
17 QuartzCore 0x004bee71 _ZN2CA11Transaction6commitEv + 393
18 QuartzCore 0x004bf544 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
19 CoreFoundation 0x0323c4ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
20 CoreFoundation 0x0323c41f __CFRunLoopDoObservers + 399
21 CoreFoundation 0x0321a344 __CFRunLoopRun + 1076
22 CoreFoundation 0x03219ac3 CFRunLoopRunSpecific + 467
23 CoreFoundation 0x032198db CFRunLoopRunInMode + 123
24 GraphicsServices 0x034ce9e2 GSEventRunModal + 192
25 GraphicsServices 0x034ce809 GSEventRun + 104
26 UIKit 0x00d19d3b UIApplicationMain + 1225
27 Skirr 0x000056a2 main + 130
28 libdyld.dylib 0x06896725 start + 0
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
}
Thanks in advance

Interpreting the error message:
The error occurred in the class: Skirr method: -[SlideViewController viewDidLoad] and the error was adding a nil object.
Look at that method and find a place where something is being added to an array.

Related

How to Drag an Image with Gesture Recognition Xcode

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];

What is this new UI component and how do i code it

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.

UITextView setEditing:YES makes the control of the TextView scroll?

I have a UITableViewCell that has an integrated UITextView. The goal is to make a cell that auto-expands while editing. The issue right now is that when the UITableViewController sends setEditing:YES, the UITextView scrolls and clips some of the text at the top.
I'm sure there is a better way to do this but I just don't know how...
#import "PLTextViewCell.h"
#implementation PLTextViewCell
#synthesize delegate=_delegate;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
_textView = [[UITextView alloc] initWithFrame:CGRectMake(90, 0, 200, 80)];
[_textView setEditable:NO];
[_textView setFont:[UIFont systemFontOfSize:15.0]];
[_textView setDelegate:self];
[_textView setScrollEnabled:NO];
[[self contentView] addSubview:_textView];
}
return self;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[_textView setEditable:editing];
[_textView scrollRangeToVisible:NSMakeRange(0, 1)];
[self textViewDidChange:_textView];
}
- (void)dealloc {
[_textView dealloc];
[super dealloc];
}
- (void)setTextValue:(NSString *)value {
[_textView setText:value];
[self textViewDidChange:_textView];
}
- (NSString *)textValue {
return [_textView text];
}
- (CGFloat)cellHeight {
CGSize mySize = [_textView contentSize];
NSLog(#"cell height: %f", mySize.height);
return mySize.height;
}
#pragma mark -
#pragma mark Text view delegate
- (void)textViewDidChange:(UITextView *)textView {
CGSize mySize = [_textView contentSize];
if (mySize.height > self.bounds.size.height) {
[textView scrollRectToVisible:CGRectMake(0,textView.contentSize.height-1,1,1) animated:NO];
if ([self delegate] != nil) {
[[self delegate] tableViewCellDidChangeHeight:self];
}
[textView setFrame:CGRectMake(90, 0, mySize.width, mySize.height)];
[self setNeedsLayout];
}
}
#end
Then the Table view implements a delegation method:
- (void)tableViewCellDidChangeHeight:(PLTextViewCell *)cell {
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
Any ideas? Am I doing this all wrong?
Turns out that it was the UIEdgeInset combined with my textview not being tall enough. My mistake!

Scroll View in Grid TableView

I'm completely new to iPhone development. I have a query regarding how to implement scroll view in table view. I'm using following code
#import <UIKit/UIKit.h>
#class ScrollViewViewController;
#interface ScrollViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ScrollViewViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ScrollViewViewController *viewController;
#end
////////////////////////////////////////////
#import "ScrollViewAppDelegate.h"
#import "ScrollViewViewController.h"
#implementation ScrollViewAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
///////////////////////////
#import <UIKit/UIKit.h>
#interface MyTableCell : UITableViewCell {
NSMutableArray *columns;
}
- (void)addColumn:(CGFloat)position;
#end
//////////////////////////
#import "MyTableCell.h"
#implementation MyTableCell
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
columns = [NSMutableArray arrayWithCapacity:5];
[columns retain];
}
return self;
}
- (void)addColumn:(CGFloat)position {
[columns addObject:[NSNumber numberWithFloat:position]];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// just match the color and size of the horizontal line
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0);
CGContextSetLineWidth(ctx, 0.25);
for (int i = 0; i < [columns count]; i++) {
// get the position for the vertical line
CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];
CGContextMoveToPoint(ctx, f, 0);
CGContextAddLineToPoint(ctx, f, self.bounds.size.height);
}
CGContextStrokePath(ctx);
[super drawRect:rect];
}
- (void)dealloc {
[super dealloc];
[columns dealloc];
}
#end
//////////////////////
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
}
#end
/////////////////
#import "RootViewController.h"
#import "MyTableCell.h"
#implementation RootViewController
#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER #"TrailItemCell"
#define SECOND_CELL_IDENTIFIER #"RegularCell"
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.title = #"Grids!";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return 19;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = [NSString stringWithFormat:#"MyIdentifier %i", indexPath.row];
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 30.0,
tableView.rowHeight)] autorelease];
[cell addColumn:40];
label.tag = LABEL_TAG;
label.font = [UIFont systemFontOfSize:12.0];
label.text =#"S.NO";// [NSString stringWithFormat:#"%d", indexPath.row];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor redColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(40.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:120];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product ID";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(134.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:220];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(230.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:310];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(320.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:400];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Product";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
#end
////////////
#import <UIKit/UIKit.h>
#interface ScrollViewViewController : UIViewController<UIScrollViewDelegate> {
}
#end
/////////////
#import "ScrollViewViewController.h"
#import "RootViewController.h"
#implementation ScrollViewViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
RootViewController *RootViewControllerLink = [[RootViewController alloc]initWithNibName:#"RootViewController" bundle:nil];
RootViewControllerLink.view.tag = 100;
/* UIImageView *imgView = [[[UIImageView alloc] initWithImage:
[UIImage imageNamed:#"winkler-gnu-blue.png"]] autorelease];
imgView.tag = 100;
*/
UIScrollView *scrollView = [[[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,320,480)] autorelease];
scrollView.delegate = self;
scrollView.minimumZoomScale = 0.25;
scrollView.maximumZoomScale = 2;
scrollView.bounces = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.contentSize = RootViewControllerLink.view.frame.size;
scrollView.contentOffset =
CGPointMake((RootViewControllerLink.view.frame.size.width-320)/2,
(RootViewControllerLink.view.frame.size.height-480)/2);
[scrollView addSubview:RootViewControllerLink.view];
self.view = scrollView;
}
/*- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [self.view viewWithTag:100];
}
- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
return YES;
}// default returns YES
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
*/
// not called if canCancelContentTouches is NO. default returns YES if view isn't UIControl
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In above code if I set scroll for UIIMage then it works but if I set scroll view for RootViewController then it doesn't work.
I didn't read your code, please reformat it so others can read it easily.
What do you mean by a UIScrollView in an UITableView? Inside the cells? Still I don't get it.
FYI UITableView inherits from UIScrollView ...
What functionality do you exactly want to achieve?
I will recommend to read some of the samples given by Apple. There are very good and extensive examples specially regarding UIKit.

How to add line numbers to a UITextView?

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.