UIViews Overlap after adding Gravity and Collision behaviour - objective-c

I am trying to stack up uiviews on click of a button. I've also added Gravity & Collision behaviour using UIKit dynamics. The problem as you can see from the image (http://pho.to/7nVJI) is, the lower most green block and the block on top of that seems to be overlapping. Here is the ViewDidLoad method :
`- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *moveIt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
moveIt.frame = CGRectMake(200, 50, 70, 30);
[moveIt addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:moveIt];
moveIt.titleLabel.text = #"Hit it";
moveIt.titleLabel.textColor = [UIColor whiteColor];
moveIt.backgroundColor = [UIColor blueColor];
UIButton *addBlockButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
addBlockButton.frame = CGRectMake(20, 50, 70, 30);
[addBlockButton addTarget:self action:#selector(addBlock:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:addBlockButton];
addBlockButton.backgroundColor = [UIColor orangeColor];
animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
newBlockYCoordiante = self.view.bounds.size.height-BLOCKHEIGHT;
UIView *basicBlock = [[UIView alloc] initWithFrame:CGRectMake(64, newBlockYCoordiante, BLOCKWIDTH, BLOCKHEIGHT)];
basicBlock.layer.borderWidth = 1;
basicBlock.tag = 100;
basicBlock.layer.borderColor = [UIColor greenColor].CGColor;
basicBlock.backgroundColor = [UIColor clearColor];
[self.view addSubview:basicBlock];
newBlockYCoordiante = newBlockYCoordiante - BLOCKHEIGHT;
if (collisonBehaviour == nil) {
collisonBehaviour = [[UICollisionBehavior alloc] initWithItems:#[basicBlock]];
collisonBehaviour.translatesReferenceBoundsIntoBoundary = YES;
collisonBehaviour.collisionDelegate = self;
[animator addBehavior:collisonBehaviour];
}
if (gBehaviour == nil) {
gBehaviour = [[UIGravityBehavior alloc] initWithItems:#[basicBlock]];
[animator addBehavior:gBehaviour];
}
}`
And here is how I add new blocks on top of the previous blocks :
- (void) addBlock :(id)sender
{
UIView *basicBlock = [[UIView alloc] initWithFrame:CGRectMake(64, newBlockYCoordiante, BLOCKWIDTH, BLOCKHEIGHT)];
basicBlock.layer.borderWidth = 1;
basicBlock.layer.borderColor = [UIColor orangeColor].CGColor;
basicBlock.backgroundColor = [UIColor clearColor];
[self.view addSubview:basicBlock];
newBlockYCoordiante = newBlockYCoordiante - BLOCKHEIGHT;
[gBehaviour addItem:basicBlock];
[collisonBehaviour addItem:basicBlock];
}
How do i ensure that these blocks doesn't overlap while stacking up. This overlapping causes another issue, when I add another tower similar to this next to it on right and add push behaviour to the green block to move it towards right, instead of moving only the adjacent block from the second tower it also moves the second last block from the 2nd tower.
Any pointers/help is appreciated. Thanks in advance :).

I believe UIDynamics adds a little "give" to objects and friction so that when they collide and move they act more realistically. You may be able to reduce this, by using UIDynamicItemBehavior and reducing elasticity and bounce, but I'm not sure.
Long story short UIDynamics tends to be an imprecise system and if you're looking to animate interface items in, I'd recommend using dynamics only until items reach their desired location and then removing their behaviors and setting their exact locations :)

Related

iOS8 UIButton title disappear

I have a button in my app that is perfectly visible on iOS7. But when I switch to iOS8 the title label for this button does not appear. And I can see only border around the button.
Here is the code that makes the button. Could someone give me a clue where the problem is?
UIButton *problem = [[UIButton alloc] initWithFrame:frame];
[problem addTarget:self action:#selector(problemButton:) forControlEvents:UIControlEventTouchUpInside];
problem.backgroundColor = [UIColor whiteColor];
[problem setTitle:NSLocalizedString(#"ReportAProblem", nil) forState:UIControlStateNormal];
problem.titleLabel.textColor = CUSTOM_DARK_GRAY_COLOR;
[[problem layer] setBorderWidth:1.0f];
[[problem layer] setBorderColor:CUSTOM_DARK_GRAY_COLOR.CGColor];
problem.layer.cornerRadius = 5;
problem.clipsToBounds = YES;
I found an answer for this question but immediately there is another:
I encounter the very same problem with some of my UILabels, for example:
self.label = [[UILabel alloc] initWithFrame:labelFrame];
self.label.numberOfLines = 1;
self.label.adjustsFontSizeToFitWidth = YES;
self.label.textAlignment = NSTextAlignmentCenter;
self.label.textColor = self.textColor;
CGFloat fontSize = self.bounds.size.height / 5;
self.label.font = [UIFont systemFontOfSize:fontSize];
You should use - (void)setTitleColor:(UIColor *)color forState:(UIControlState)state instead of titleLabel.textColor.
Second problem: Why are you trying to set a ratio of your view height as a font size ? Maybe doing it with your label makes more sense. CGFloat fontSize = self.label.bounds.size.height / 5; Anyway what you usually want to do is have a fixed font size and adapt the label frame around it.

iOS 7 BarButtonItem with image and title

I'm trying to figure out how can I achieve something like this:
This is a toolbar and I'd like to keep the button title text without having to create the whole image with icon AND text. How can I add the icon to the left of the UIBarButtonItem while keeping the text set with:
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];
EDIT
This is what I achieved with the following code:
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"Test"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[customButton sizeToFit];
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
Two issues here: the first is the size of the UIButton and the second is that, as you can see from the gif, the button doesn't animate properly when I tap inside the button and when I release the tap. Any ideas?
You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem
Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.
For more info, see the documentation for initWithCustomView:.
You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.
I was not satisfied with all solutions found on stack overflow becauseI like how UIBarButtonItenm convert images so they are displayed correctly and they can be changed with tint colour. So i discovered this solution that I can use nicely with not much code... End effect is similar to toolbar in facebook and other current apps...
When you change tint colour of view contained in UIBArButtonItem colours of image and title change accordingly, really cool , I do not have to create special images at all.
This code is called from each button like that Competition Button, and also Button is set as referencing outlet...
- (void)selectButton:(UIButton *)sender {
_competitionButton.superview.tintColor = [UIColor lightGrayColor];
_usersButton.superview.tintColor = [UIColor lightGrayColor];
_managementButton.superview.tintColor = [UIColor lightGrayColor];
sender.superview.tintColor = [UIColor whiteColor];
}
- (IBAction)onCompetitionButtonClick:(UIButton *)sender {
[self selectButton:sender];
[_scrollView scrollToPage:0 of:3];
}
In Button like that titled Competition there is only title and in bar button item there is image... This is how I have setup it and it works , maybe there are also other possibilities..
So I managed to do my solution programatically... Some users where complaining it does not work ... So how to create UTToolbar with image and item so that you can change color of button by tint and it magically alters image as well as title label ? My UI editor solution works for sure...
In this code can clarify things more and you can do it programatically either...
- (void)loadToolbar {
NSMutableArray *items = NSMutableArray.new;
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
for (uint pageIndex = 0; pageIndex < _controllers.count; ++pageIndex) {
UIView *itemView = [UIView.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemView.backgroundColor = [UIColor clearColor];
itemView.tintColor = [UIColor orangeColor];
[itemView addSubview:[self createToolbarForItemView:pageIndex]];
[itemView addSubview:[self createButtonForItemView:pageIndex]];
UIBarButtonItem *item = [UIBarButtonItem.alloc initWithCustomView:itemView];
item.style = UIBarButtonItemStylePlain;
[items add:item];
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
}
[_toolbar setItems:items];
}
- (UIButton *)createButtonForItemView:(uint)pageIndex {
UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeSystem];
itemButton.frame = CGRectMake(0, 0, 100, 44);
itemButton.titleLabel.font = [UIFont systemFontOfSize:11];
itemButton.contentEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
itemButton.text = [_controllers[pageIndex] tabTitle];
itemButton.touchUp = ^(UIButton *sender) {
for (UIButton *button in _buttons) button.superview.tintColor = UI.toolBarInactiveButtonTextColor;
sender.superview.tintColor = UI.toolBarActiveButtonTextColor;
[self showPage:pageIndex];
};
[_buttons add:itemButton];
return itemButton;
}
- (UIToolbar *)createToolbarForItemView:(uint)pageIndex {
UIToolbar *itemToolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemToolbar.tintColor = nil;
itemToolbar.barStyle = _toolbar.barStyle;
itemToolbar.translucent = _toolbar.translucent;
UIBarButtonItem *imageItem = [_controllers[pageIndex] tabImageItem];
imageItem.style = UIBarButtonItemStylePlain;
imageItem.tintColor = nil;
imageItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
itemToolbar.items = #[
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil],
imageItem,
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]
];
return itemToolbar;
}
I solved this problem as follows:
[Button **setTitleColor**:[UIColor colorWithRed:129/255.0f green:124/255.0f blue:110/255.0f alpha:1.0f] forState:**UIControlStateHighlighted**];

Can't see the button

- (void)viewDidLoad{
int leftBorder = 80;
int topBorder = 160;
int width = 150;
int height = 50;
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(leftBorder, topBorder, width, height)];
myView.layer.cornerRadius = 5;
myView.backgroundColor = [UIColor redColor];
[self.view addSubview:myView];
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testButton.frame = CGRectMake(0, 0, 50, 50);
[testButton setTitle:#"testButton" forState:UIControlStateNormal];
[testButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.myView addSubview:self.testButton];
self.myView.hidden = YES;
[super viewDidLoad];
}
Hi, sorry for stupid question! I'm newby in xcode. Why I didn't see this button? And How can I hide button after click? I need button inside the frame.
Simple remove self.myView.hidden = YES;
To add you click listener, two solution:
By code in your viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
[mybutton addTarget:self action:#selector(myButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
}
- (void)myButtonClick:(id)sender {
myButton.hidden = YES;
}
Or via interface Builder (preferred), The easiest way is to actually define the handler/action in Xcode using the IBAction declaration in the interface file (add the declaration just before the #end statement). Then attach the action to the button
you are adding self.testButton instead of the created testButton.
[self.myView addSubview:testButton];
you did not assign myView to your property.
[self.view addSubview:myView]; self.myView = myView;
remove self.myView.hidden = YES;
Another remark:
You should usually call super as early as possible. Otherwise, the superclass may interfere with your own implementation.
There are several issues in your code.
You add testButton as subview to self.myView. Then you hide self.myView. As a result neither self.myview nor its subviews will be visible.
You get confused with your local varialbles and instance varialbes. Apparently there is an instance variable and property myView. Otherwise you coudn't use self.myView. And you declare a local variable myView, which is not the same as the instance variable. This may well be perfectly ok. But I got a guts feeling that you did this not intentionally. Your self.myView may well be nil at the point in time where you add the subview. And even the subview self.testButton may be nil. That will compile file and execute fine but nothing does happen actually.
The same for testButton.
I suggest to change the code a bit, assuming there are properties for myView and testButton of the appropriate types:
self.myView = [[UIView alloc] initWithFrame:CGRectMake(leftBorder, topBorder, width, height)];
self.myView.layer.cornerRadius = 5;
self.myView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.myView];
self.testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.testButton.frame = CGRectMake(0, 0, 50, 50);
[self.testButton setTitle:#"testButton" forState:UIControlStateNormal];
[self.testButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.myView addSubview:self.testButton];
self.myView.hidden = NO;

UIButton touch up inside event only fired if done in title

I am customizing a UITableViewCell with several subviews:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_mainView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 40.0f)];
_hiddenOptionsView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 40.0f)];
_menuView = [[CellMenuView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 20.0f)];
[self addSubview:_menuView];
[self addSubview:_hiddenOptionsView];
[self addSubview:_mainView];
}
return self;
}
The class CellMenuView is a UIView subclass which has two UIButtons with their counterpart target actions setup on initialization:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIImageView *background = [[UIImageView alloc] initWithFrame:frame];
[background setImage:[UIImage imageNamed:#"cell_menu_bg.png"]];
[self addSubview:background];
CGFloat buttonX = frame.origin.x;
CGFloat buttonY = frame.origin.y + 3.0f;
CGFloat buttonWidth = frame.size.width / 2.0f;
CGFloat buttonHeight = 10.0f;
_editButton = [UIButton buttonWithType:UIButtonTypeCustom];
_editButton.frame = CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight);
_editButton.backgroundColor = [UIColor clearColor];
_editButton.titleLabel.shadowColor = [UIColor blackColor];
_editButton.titleLabel.shadowOffset = CGSizeMake(0.0f, -1.5f);
_editButton.titleLabel.font = [UIFont boldSystemFontOfSize:22.0f];
[_editButton setTitle:#"Edit" forState:UIControlStateNormal];
[_editButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_editButton addTarget:self action:#selector(editButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_editButton];
_fireButton = [UIButton buttonWithType:UIButtonTypeCustom];
_fireButton.frame = CGRectMake(buttonWidth, buttonY, buttonWidth, buttonHeight);
_fireButton.backgroundColor = [UIColor clearColor];
_fireButton.titleLabel.shadowColor = [UIColor blackColor];
_fireButton.titleLabel.shadowOffset = CGSizeMake(0.0f, -1.5f);
_fireButton.titleLabel.font = [UIFont boldSystemFontOfSize:22.0f];
[_fireButton setTitle:#"Fire" forState:UIControlStateNormal];
[_fireButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_fireButton addTarget:self action:#selector(fireButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_fireButton];
return self;
}
}
I have implemented the target action methods but they aren't being executed. Instead, didSelectRowAtIndexPath: takes precedence over the touch up events inside buttons every time I pressed one of them.
The only way I have been able to fire the events on buttons is making sure that one of the letters in UIButton's title is touched (using the simulator, of course).
I must say that _menuView is hidden behind the other subviews and shown below the cell when a custom accessory button in cell is pressed. It appears by modifying the Y origin and disappears by setting it to 0.0f again.
I think it may be related to the view hierarchy, because I haven't had any problems in the past by adding buttons directly to the cell. But I'm just guessing here.
How can I make the events on buttons take precedence over the didSelectRowAtIndexPath: method?
Thanks!
Implement
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
And return nil for the indexPath you don't want selected; this will prevent didSelectRowAtIndexPath from being called on that cell, and (hopefully), your custom action will be called.
Update: After implementing this myself (adding borders to the buttons), this is what I have.
The code to achieve this (which is different than yours), is as follows:
CellMenuView.m
self.backgroundColor = [UIColor blackColor];
_editButton.layer.borderColor = [UIColor whiteColor].CGColor;
_editButton.layer.borderWidth = 2;
_fireButton.layer.borderColor = [UIColor whiteColor].CGColor;
_fireButton.layer.borderWidth = 2;
UITableViewCell subclass
// Change in height to make it taller
_menuView = [[TestBtn alloc] initWithFrame:CGRectMake(0.0f, 20.0f, 320.0f, 60.0f)];
UITableViewController subclass
self.tableView.rowHeight = 100;
After testing, mine works as expected. If I click within the white squares, the button action is performed as normal, and didSelectRowAtIndexPath is not called. didSelectRowAtIndexPath is only called when I click outside of the buttons.
I think the issue here might be your button heights/frames, as well as your row height. Add borders to your buttons, to check its clickable area, and increase the height of the button to increase the clickable area.

UINavigationController rightbarbuttonitem not showing

after going through the questions related to UINavigationController item i came to post my exact problem ..
firstly i am not add a UINavigationController in MainWindow.xib i created and adding UINavigationController in AppDelegate file
after that in a UIViewController (not in rootViewController) class I have to add a rightbarbutton of Done type I am
adding it in a searchbarDelegate Method showing as bold:-
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from teh detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(exhibDataObj.searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.theTableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
exhibDataObj.searching = true;
letUserSelectRow = NO;
self.theTableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)];
}
but this never works .
Any help will be more appreciable.
I've tested your code real quick and it seems to be working fine for me, however, I've had the same problem once back then it turned out I was setting the rightBarButtonItem to nil in my viewDidLoad method after setting it to a button. you should make sure your not making the same mistake somehow.
However if that does not work for you you can always try setting a custom button to it:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"done.png"]];
[button addTarget:self action:#selector(doneButtonClicked) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationController.visibleViewController.navigationItem.rightBarButtonItem = customItem;