Adding UIPangesture for UIButton within UIScrollview to move over the all view - objective-c

In my project i am having scroll at bottom and table at top.
Inside scrollview i am adding 10 buttons.for each button i had pan gesture to move around the screen.when the button intersect with table is will add a picture in tableview.
But the pan is working within the scroll.how to make it move over view
MY coding is:
downscroll=[[UIScrollView alloc]initWithFrame:CGRectMake(24, 635, 980, 100)];
downscroll.backgroundColor=[UIColor redColor];
downscroll.contentSize=CGSizeMake(990, 100);
[self.view addSubview:downscroll];
for(int i=1;i<=8;i++)
{
b1=[UIButton buttonWithType:UIButtonTypeCustom];
b1.frame=CGRectMake(30+px, 0, 80, 80);
[b1 setImage:[UIImage imageNamed: [NSString stringWithFormat:#"Icon%i.png",i]] forState:UIControlStateNormal];
[downscroll addSubview:b1];
// [self.view sendSubviewToBack:b1];
// [self.view bringSubviewToFront:b1];
[groupbutton addObject:b1];
panRecognizer3= [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(move:)];
[b1 setUserInteractionEnabled:YES];
b1.exclusiveTouch=YES;
img.tag=i;
[b1 addGestureRecognizer:panRecognizer3];
px=px+120;
}
When i add my buttons directly without scroll scrollview it works fine.But i need to add button scrollview
please help with proper code. Thanks in advance.

Here is the way I used in my application
In my code I follow the below steps
In UIPanGestureRecognizer starting point I add the button to the self.view from scrollView
Drag button by using the translationInView method
3.In UIPanGestureRecognizer end state I'll check if the button dropped in the destination View.If so do your required task else add the button at the same position in the scrollView
`MoveControl` is a UIPanGestureRecognizer method
- (void)MoveControl:(UIPanGestureRecognizer *)recognizer
{
UIButton *vew=(UIButton *)[recognizer view];
CGPoint newCenter = [recognizer translationInView:self.view];
if (recognizer.state==UIGestureRecognizerStateBegan) {
CGPoint point=vew.frame.origin;
[vew setTitle:NSStringFromCGPoint(point) forState:UIControlStateSelected];
CGRect rect=[self.view convertRect:[vew frame] fromView:[vew superview]];
[vew setFrame:rect];
[self.view addSubview:vew];
CGPoint point1=vew.frame.origin;
[vew setTitle:NSStringFromCGPoint(point1) forState:UIControlStateDisabled];
}
else
{
CGPoint oldcentre= CGPointFromString([vew titleForState:UIControlStateDisabled]);
CGRect rect=vew.frame;
CGPoint origin=rect.origin;
origin.x=(newCenter.x+oldcentre.x);
origin.y=(newCenter.y+oldcentre.y);
rect.origin=origin;
vew.frame=rect;
if (CGRectIntersectsRect(rect, [pageOriginalContainer frame])) {
[YourTable setBackgroundColor:[UIColor lightGrayColor]];//Notifying that the tableView will accept the icon
}
else
{
[YourTable setBackgroundColor:[UIColor clearColor]];
}
}
if (recognizer.state==UIGestureRecognizerStateEnded)
{
CGRect rect=[vew frame];
if (CGRectIntersectsRect(rect, [pageOriginalContainer frame])) {
//your method of adding the Image to table
}
else//else part is means for if user dropped dragging somewhere else other than Table
{
CGPoint point=CGPointFromString([vew titleForState:UIControlStateSelected]);
CGRect frame=vew.frame;
frame.origin=point;
vew.frame=frame;
[pageCopyContainer addSubview:vew];
// [NSFileManager defaultManager]
}
}
}

Related

Why does my textField disappear?

I do some practice with iPhone4S about UITextField on iOS 7.1.2.
Interface:
The interface of the first version is simple, which just has a custom UITextField named MyUITextField and a UIButtom object that use to cancel the search operation. Inside the textField, its leftView property is initially set to a UIButton object, which background image is a magnifying glass. When users tap in the textField, that magnifying glass button will be removed and the leftView property will also set to a new UIButton object, which background image is a inverted triangle. When users tap the triangle button, app will create a new view object.
Main code:
//In this version,the textField's original frame property is set to (10,40,250,30)
//and the main operations are like this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTextField.delegate = self;
self.myTextField.leftViewMode = UITextFieldViewModeUnlessEditing;
self.myTextField.leftView = [self creCustomSearchBar];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyBoardWillAppear:)
name:#"UIKeyboardWillShowNotification"
object:nil];
[self.cancleSearchButton addTarget:self
action:#selector(cancleSearch:)
forControlEvents:UIControlEventTouchUpInside];
}
/*when tapping in the textField,keyboard will appear*/
- (void)keyBoardWillAppear:(NSNotification *)notification
{
CGRect newLeftViewIndicatorRect = CGRectMake(20,5,20,20);
UIButton *newLeftViewIndicator = [[UIButton alloc] initWithFrame:newLeftViewIndicatorRect];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:#"searchbar_textfield_down_icon#2x" ofType:#"png"];
[newLeftViewIndicator setBackgroundImage:[UIImage imageWithContentsOfFile:imagePath] forState:UIControlStateNormal];
[newLeftViewIndicator addTarget:self action:#selector(createActuralLeftView:) forControlEvents:UIControlEventTouchUpInside];
self.myTextField.leftView = newLeftViewIndicator;
/*in the second verson need to call */
//[self adjustViewFrame];
[self.cancleSearchButton setTitle:#"取消" forState:UIControlStateNormal];
}
- (void)createActuralLeftView:(UIButton *)leftViewButton
{
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(tapRegionAboveKeyboard:)];
[self.view addGestureRecognizer:tapGesture];
NewLeftView *leftView = [[NewLeftView alloc] initWithFrame:CGRectMake(10, 80, 140, 100)];
leftView.delegate = self;
[self.view addSubview:leftView];
}
- (void)tapRegionAboveKeyboard:(UITapGestureRecognizer *)tapGesture
{
for (UIView *v in self.view.subviews) {
if ([v isKindOfClass:[NewLeftView class]]) {
[v removeFromSuperview];
[self.view removeGestureRecognizer:tapGesture];
return;
}
}
}
//in the second version need to call
- (void)adjustViewFrame
{
[[self.myTextField class] animateWithDuration:0.05 animations:^{
[self.myTextField setFrame:CGRectMake(self.myTextField.frame.origin.x, 40, self.myTextField.frame.size.width, self.myTextField.frame.size.height)];
}];
[[self.cancleSearchButton class] animateWithDuration:0.05 animations:^{
[self.cancleSearchButton setFrame:CGRectMake(self.cancleSearchButton.frame.origin.x, 40, self.cancleSearchButton.frame.size.width, self.cancleSearchButton.bounds.size.height)];
}];
}
In the first version things work well.
But in the second version, I set the textField frame property to (10,260,250,30), so I need to call the adjustViewFrame method in the keyBoardWillAppear: to reposition the textField in case of obscuring by the keyboard.
Here comes the problem: the textField's position is correctly moved to the right place, but when I tap the inverted triangle button, the textField disappeared.
I can't figure out what's going wrong here.

Remove subview when touched outside of subview

My situation is a little more complicated than the others listed.
I have a UITableView that takes up most of the screen.
Each row pops up a subview that contains more profile information. When the screen is clicked again this subview disappears. This works perfectly.
In the Navigation Bar I have a button that will display a small menu.
- (IBAction)menuButtonClicked:(UIBarButtonItem *)sender {
//If menuView exists and Menu button is clicked, remove it from view
if (self.menuView) {
self.tableView.userInteractionEnabled = true;
[self.menuView removeFromSuperview];
self.menuView = Nil;
}
//Menu View doesn't exist so create it
else {
// Create the Menu View and add it to the parent view
self.menuView = [[[NSBundle mainBundle] loadNibNamed:#"MenuView" owner:self
options:nil] objectAtIndex:0];
self.menuView.layer.cornerRadius = 20.0f;
self.menuView.layer.borderWidth = 3.0f;
self.menuView.layer.borderColor = [UIColor whiteColor].CGColor;
self.menuView.frame = CGRectMake(0, 64, self.menuView.frame.size.width,
self.menuView.frame.size.height);
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[self.menuView addGestureRecognizer:singleTap];
//Disable Selection of Profiles while Menu is showing
self.tableView.userInteractionEnabled = false;
//Add MenuView to View
[self.view addSubview: self.menuView];
}
}
//Removed Sub Views from View when tapped
-(void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture{
if(self.profileView){
[self.profileView removeFromSuperview];
self.profileView = Nil;
}
if(self.menuView) {
self.tableView.userInteractionEnabled = true;
[self.menuView removeFromSuperview];
self.menuView = Nil;
}
}
Now I want to dismiss this menus if the menu button is clicked again (working in above code) but also when the user touches out of the menu and on the tableView or navbar. If the menu is displayed, I don't want the tableView to display it's profile subview (working in above code) but just remove the menuView. I can't get the menuView to go away if I touch the tableView.
Can anyone point me in the right direction?
Make a new transparent overlay view sized to cover the entire screen. Add your menuView as a subview of the overlay, then add the overlay as a subview of your main window. Put a tap gesture recognizer on the overlay that will dismiss it when tapped.
You may need to set cancelsTouchesInView to NO on your gesture recognizer if buttons on your menu view are not working.
Roughly this (please excuse typos, I haven't compiled this):
- (void)showMenu
{
self.overlay = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
overlay.backgroundColor = [UIColor clearColor];
self.menuView = /* code to load menuView */;
[overlay addSubview:self.menuView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(onSingleTap:)];
tap.cancelsTouchesInView = NO;
[overlay addGestureRecognizer:tap];
[self.tableView.window addSubview:overlay];
}
- (void)handleSingleTap:(UITapGestureRecognizer *)sender
{
[self.overlay removeFromSuperview];
}
You might also want to add a swipe gesture recognizer to also dismiss the overlay, as someone may attempt to scroll the table expecting the menu to be dismissed.
While trying to make my own custom topdown-slide menu using my own custom NIB file, I found that this can be achieved by many techniques. I would like to suggest and share a different solution which is very similar but is created with a custom button on the background.
I've been looking around but could not find answers mentioning this.
This is very similar to the tap recogniser except for one thing - tap recogniser spreads all over the layout (including subviews), while using a layer of custom button allows you to interact with the top view and dismiss/ remove it from superview when clicking on lower layer (when lower layer is the background button). This is how I did it:
You create the layout
You add a UIButton with type UIButtonTypeCustom to the layout
You frame this layout over the view you wish to be responsive to that tap/click
You add your menu view on top of that layout and animate your menu to appear
- (void)showMenuViewWithBackgroundButtonOverlay
{
self.backgroundButton = ({
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = self.view.frame;
[button addTarget:self action:#selector(toggleAppMenu) forControlEvents:UIControlEventTouchUpInside];
button;
});
if (!self.menu) {
self.menu = [self createMenu]; // <-- get your own custom menu UIView
}
if (!self.overlay) {
self.overlay = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.overlay.backgroundColor = [UIColor clearColor];
[self.overlay addSubview:self.backgroundButton];
[self.overlay addSubview:self.menu];
[self.view addSubview:self.overlay];
}
[self toggleAppMenu];
}
And the toggleAppMenu:
- (void)toggleAppMenu
{
CGRect nowFrame = [self.menu frame];
CGRect toBeFrame = nowFrame;
CGFloat navHeight = self.navigationController.navigationBar.frame.size.height;
CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
if (self.showingMenu) {
toBeFrame.origin.y = toBeFrame.origin.y-nowFrame.size.height-navHeight-statusBarHeight;
[UIView animateWithDuration:0.5 animations:^{
[self.menu setFrame: toBeFrame];
}completion:^(BOOL finished) {
self.showingMenu = !self.showingMenu;
[self.view endEditing:YES];
[self.overlay removeFromSuperview];
self.overlay = nil;
NSLog(#"menu is NOT showing");
}];
}
else{
toBeFrame.origin.y = navHeight+statusBarHeight;
[UIView animateWithDuration:0.5 animations:^{
[self.menu setFrame: toBeFrame];
}completion:^(BOOL finished) {
self.showingMenu = !self.showingMenu;
NSLog(#"menu is showing");
}];
}
}
I hope this will be helpful for someone.
Works on Swift 5
I create custom view and I want it hide by tap outside subview. Maybe it can help for someone or anybody can suggest a better way :)
// create tap for view
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(animateOut))
self.addGestureRecognizer(tapGesture)
// create tap for subview
let tapGesture2 = UITapGestureRecognizer(target: self, action: nil)
container.addGestureRecognizer(tapGesture2)

Custom titleView in UINavigationItem doesn't adjust height if offscreen during rotation

I have a custom titleView for a UINavigationItem with the autoresizeMask set to adjust the width and height of the view. If I rotate the device while it is visible, the height is automatically adjusted for the shorter landscape nav bar. However, if I push a new view controller, rotate the device, and then come back to the one with the custom titleView, it doesn't recognize the change in height. For now I've added the following code to the viewWillAppear: method
- (void) viewWillAppear:(BOOL)animated {
CGRect frame = self.titleButton.frame;
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
frame.size = CGSizeMake(self.navigationController.navigationBar.frame.size.width - 150.0f, 44.0f);
} else {
frame.size = CGSizeMake(self.navigationController.navigationBar.frame.size.width - 150.0f, 32.0f);
}
self.titleButton.frame = frame;
...
}
This fixes the issue, but I'm wondering if I'm missing some property to get things adjusting on their own properly. The custom view is a UIButton:
titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[titleButton setFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width - 150.0f, 44.0f)];
[[titleButton titleLabel] setFont:[UIFont boldSystemFontOfSize:18]];
[titleButton setBackgroundImage:navbarButtonImage forState:UIControlStateNormal];
[titleButton setBackgroundImage:navbarButtonPressedImage forState:UIControlStateSelected];
[titleButton setBackgroundImage:navbarButtonPressedImage forState:UIControlStateHighlighted];
titleButton.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
titleButton.autoresizesSubviews = YES;
Is there a better way to setup this view?

Overlay not scrolling with UITableView - iOS

I have a UITableView class that uses the following methods to call a loading overlay when going to the next screen. The problem is that this loading screen does not scroll with the list... So if you scroll a little bit and click on something, the loading screen doesn't show (because it's at the top). How can I get the loading screen to stay on top of the UITableView at all times? Please know that each UITableView is contained within a UINavBar, which is contained within a UITabBar. Here is my code:
-(void)createLoadScreen
{
CGRect screenRect = [self.view bounds];
CGRect overlayFrame = CGRectMake(0.0, 0.0, screenRect.size.width, screenRect.size.height);
overlay = [[UIView alloc] initWithFrame:overlayFrame];
overlay.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
CGRect frame = CGRectMake(screenRect.size.width / 2 - 25.0, screenRect.size.height / 2 - 70, 25.0, 25.0);
loading = [[UIActivityIndicatorView alloc] initWithFrame:frame];
[loading setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
[loading sizeToFit];
loading.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);
loading.hidesWhenStopped = YES;
[overlay addSubview:loading];
}
-(void)showActivityIndicator
{
[self.view addSubview:overlay];
[loading startAnimating];
}
-(void)removeActivityIndicator {
[loading stopAnimating];
[overlay removeFromSuperview];
}
Are you using a UITableViewController?
You should be able to fix your issue by adding the overlay view to the table's superview instead of the table view itself. This way your overlay is actually above and separate from your scrolling table view
-(void)showActivityIndicator
{
[[self.view superview] addSubview:overlay];
[loading startAnimating];
}

UIButton does not fire target on touchUpInside unless I drag just outside?

I have a Button that when I press it, it does not fire the target selector that I've added. I've made the button Different Images, so I can see that I am Pressing it.
So here is the Funny if I Press, and drag outside of the button, but not outside of the button's immediate superView, the target selector is fired!
I've also in testing set the setClipsToBounds:YES on all the super/sub views just to be sure it was still in the views bounds. Seems to be within bounds. The dragging outside the button area seems to be omni directional, so its not like I can only tap/drag right. Left up and down work too. I can tap, drag out then back in and it works. If I don't start to drag and just tap and hold, the button highlights and then goes back to unselected state.
Here is the code for the Button. The Button is on a UIView along with a UITextView, Actually onTop Of the UITextView. The UIView that all of this is on is on a Larger View, which is on a Scaling/Scrolling view
messageLookupButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 21, 20)];
[messageLookupButton setTitle:#"junk" forState:UIControlStateNormal];
[messageLookupButton sizeToFit];
[messageLookupButton setTag:kGearButtonView];
//Get the images for the buttons
UIImage *gearButtonImage = [UIImage imageNamed:#"gear.png"];
UIImage *gearButtonImage2 = [UIImage imageNamed:#"StatusLightOn.png"];
[messageLookupButton setImage:gearButtonImage forState:UIControlStateNormal];
[messageLookupButton setImage:gearButtonImage2 forState:UIControlStateHighlighted];
[messageLookupButton addTarget:self action:#selector(gearPressed:) forControlEvents:UIControlEventTouchUpInside];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(processLookupResults:)
name:kRefreshFromPopover object:nil];
[self addSubview: messageLookupButton ];
[messageLookupButton release];
[messageLookupButton setCenter:CGPointMake(CGRectGetMaxX(elementViewContents.bounds) -kElementContentFrameOffset -(CGRectGetWidth( messageLookupButton.bounds)/2), CGRectGetMidY(elementViewContents.bounds))];
[self bringSubviewToFront:messageLookupButton];
The Scroll View has several gesture recognizers on it. Though they don't seem to interfere with other buttons and controls that I've put on the screen. Though I have a feeling its the Scroll View that is the problem.
scroll view code clip:
[scrollContentView setUserInteractionEnabled:YES];
[scrollContentView setExclusiveTouch:YES];
[scrollContentView setCanCancelContentTouches:YES];
[scrollContentView setDelaysContentTouches:YES];
I ended up Just adding the gear as an Image to the View, then created a invisible button that was the same size as the UIView that I placed the gear icon on.
-(void) addMessageLookupSelector {
// Set a default Color if there is none
if (_isMessageLookupField ){
// Add Gear to End Of Text Field
if (!messageLookupImageView) {
messageLookupImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 21, 20)];
[messageLookupImageView setTag:kGearButtonView];
[messageLookupImageView setImage:[UIImage imageNamed:#"gear.png"] ];
[self addSubview: messageLookupImageView ];
[messageLookupImageView release];
}
[self positionMessageLookupImageView ];
}
[self setNeedsDisplay];
}
- (void)makeControlEditable {
//Setup the TextField so we can edit its value, need to see if there is a Write Animation Assocated with Element
[self setTheWriteTag];
if (writeTag) {
writeInputRequestedButton = [UIButton buttonWithType:UIButtonTypeCustom];
[writeInputRequestedButton setFrame:elementViewContents.frame];
[writeInputRequestedButton setUserInteractionEnabled:YES];
[writeInputRequestedButton setEnabled:YES];
// [writeInputRequestedButton setBackgroundColor:[UIColor clearColor]];
[self addSubview: writeInputRequestedButton];
[self bringSubviewToFront:writeInputRequestedButton];
[writeInputRequestedButton addTarget:self action:#selector(wantsToEditValue:) forControlEvents:UIControlEventTouchUpInside];
}
}