how to set (make) a UIButton at bottom of my UITableview? - ios

i have two Viewcontroller. one with tableview,check button, add button at bottom . i just adjust my tableview up and kept my add button at bottom. when user press my add button it will take to next viewcontroller ( i did these thing via storyboard )
Needed:
I need my add button should be bottom to above my table view.when user scroll down my table view also it should stick at centre of my tableview.i have tried with creating seperate view ,but no use can't do that.Here this is my viewcontroller.m file:
Thanks in advance !
I used storyboard ,so i did iboutlet and synthesis it,
#interface ViewController ()
#property (strong) NSMutableArray *notes;
#end
#implementation ViewController
#synthesize tableView;
#synthesize addButton;
my viewdidload:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = #"My Notes";
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
}
when my add button presses it will move to another viewcontroller:
- (IBAction)addButtonPressed:(id)sender {
AddNoteViewController *addNoteVC = [AddNoteViewController new];
// to remove unused warning....
#pragma unused (addNoteVC)
}
Like this i need but in centre ....

Since you only want the UIButton to hover over your UITableView the solution should be quite easy.
I just created a UIButton which could the one you using.
in your method where you initialise the UIButton (e.g. viewDidLoad)
yourBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setImage:[UIImage imageNamed:#"yourIMG"] forState:UIControlStateNormal];
[yourBtn setTitle:#"+" forState:UIControlStateNormal];
yourBtn.frame = CGRectMake(0, self.view.bounds.size.height -150, buttonwidth, buttonheight);
yourBtn.center = CGPointMake(self.view.center.x, self.view.bounds.size.height -155);
[yourBtn addTarget:self action:#selector(addButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];
If this shouldn't be your solution feel free to comment this answer!
Edit
To set the width and buttonheight just add the following. Write it above the yourBtn.frame line!
CGFloat buttonwidth = 57.5;
CGFloat buttonheight = 57.5;
Edit 2.0
You need to set the segues identifier first in IB. Check: iOS and xcode: how to give a segue a "storyboard id" so that I can programmatically manipulate it
-(IBAction)addButtonPressed:(id)sender {
[self performSegueWithIdentifier:yourSegue sender:self];
}
Cheers

I think instead of frame setting in #MasterRazer's answer you should edit or add NSLayoutAttributeCenterX of your UIButton in IB. Setting that constraint of your button to 0 would make your button stays in the middle and be a clean and good solution for your problem.

Related

How to put text on left and right side of UIButton

I am new to iOS development and I recently got stucked with a problem where I am not able to set text on both sides of a button. Also I wish to add multi-line text in a button (as shown below). I have gone through lot of answers but none of them satisfied my requirement.
Any suggestion or help would greatly be appreciated, thanks!
You should definitely go with a custom UIButton class. The reason for this is that UIButton has other properties that you will want, like being recognized by iOS as a button, conform to Accessibility as a button, show up in storyboard as a button class, let your co-workers see that it actually is a button, have same/similar interface as a button, and so on.
Creating a custom button isn't that hard. Basically, just sub-class UIButton and implement awakeFromNib to set up the internals and layoutSubviews to position and size everything.
Here is an outline of how to do it...
1. Create a UIButton sub-class (.h)
Add the custom interface to the header file. It could look something like this.
#interface MyButton : UIButton
- (void)setServiceText:(NSString *)serviceText;
- (void)setPriceText:(NSString *)priceText;
- (void)setTimeText:(NSString *)timeText;
#end
2. Add controls to hold the internals of your button (.m)
The three labels and a view to use as the red sidebar. From here on you add to the code file.
#interface MyButton ()
#property (strong, nonatomic) UILabel *serviceLabel;
#property (strong, nonatomic) UILabel *priceLabel;
#property (strong, nonatomic) UILabel *timeLabel;
#property (strong, nonatomic) UIView *redSideBarView;
#end
3. Add code corresponding to the interface (.m)
Since UILabel redraws itself when we set the text property, we do not need to do more to make it appear on the button.
- (void)setServiceText:(NSString *)serviceText {
_serviceLabel.text = serviceText;
}
- (void)setPriceText:(NSString *)priceText {
_priceLabel.text = priceText;
}
- (void)setTimeText:(NSString *)timeText {
_timeLabel.text = timeText;
}
4. Implement awakeFromNib (.m)
This method will be called when Storyboard instantiate your button, so here is a good place to create your labels and do other stuff that only needs to be done once.
- (void)awakeFromNib {
[super awakeFromNib];
_sideBarView = [[UIView alloc] initWithFrame:CGRectZero];
_sideBarView.backgroundColor = [UIColor redColor];
[self addSubview:_sideBarView];
_serviceLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_serviceLabel.font = [UIFont systemFontOfSize:18.0];
[self addSubview:_serviceLabel];
_priceLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_priceLabel.textColor = [UIColor greenColor];
_priceLabel.font = [UIFont systemFontOfSize:16.0];
_priceLabel.textAlignment = NSTextAlignmentRight;
[self addSubview:_priceLabel];
_timeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_timeLabel.font = [UIFont systemFontOfSize:14.0];
[self addSubview:_timeLabel];
self.clipsToBounds = YES;
}
5. Add code to layout your button (.m)
This is the final piece of the custom button code. Note that layoutSubviews will usually be called several times during the controls lifetime, so do not add sub-views here. Use it to position and size the internals of your button. self.bounds.size represents the current size of your button, so this is a good reference for all other elements.
- (void)layoutSubviews {
// Layout sub-elements
CGFloat buttonWidth = self.bounds.size.width;
CGFloat buttonHeight = self.bounds.size.height;
_serviceLabel.frame = CGRectMake(30.0, 2.0, buttonWidth * 0.7, buttonHeight * 0.5);
_priceLabel.frame = CGRectMake(buttonWidth - 40, 5.0, 30.0, buttonHeight * 0.4);
_timeLabel.frame = CGRectMake(30.0, buttonHeight * 0.5, buttonWidth * 0.7, buttonHeight * 0.4);
_sideBarView.frame = CGRectMake(0.0, 0.0, 10.0, buttonHeight);
self.layer.cornerRadius = 10.0;
}
6. Use it!
To use it you create a regular button in Storyboard, then in the Identity Inspector, select your new button class. As usual, tie the button to a variable in your view controller class. The variable should be of your button class, of course. That's it for the design!
#property (weak, nonatomic) IBOutlet MyButton *button;
Now don't forget to set the properties.
self.button.backgroundColor = [UIColor lightGrayColor];
[self.button setServiceText:#"FULL SERVICE HAIRCUT"];
[self.button setPriceText:#"$30"];
[self.button setTimeText:#"30 minutes"];
A couple of things I didn't address here was the gradient and the drop shadow. The gradient is probably best done with a CAGradientLayer added to the button's view's layer. The drop shadow needs a bit more coding, since you are clipping the button to have rounded corners. Probably you need to add one more UIView in between to contain everything that you then clip, and then add shadow to the button view.
I wouldn't go with a UIButton but with a UIView with Labels from Xib. Tutorial on that can be found here: link.
Then you may add a target to your UIView, so that when tapping it will call some method (as would UIButton do):
yourView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
yourView.addGestureRecognizer(tap)
And method:
#objc func buttonTapped() {
// do what you need on tap here
}
Hope it helps! Please comment if you have questions.
PS. I'm not sure but from what I see you are probably building a UITableView. is it? Can you please show a design of the full screen? If you have many "buttons" like that then it's not a single "button" but a Table View.
To display multiple lines use below code
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2; // or 0(Zero)
And you need to add UIView and add tap gesture to that view and design that view like above image.
For Gestures
//Create tap gustures for view
UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onClickView:)];
[self.yourViewName addGestureRecognizer: viewTap];
- (void) onClickView:(UITapGestureRecognizer *)recognizer {
//Write your code
}
This is one approach.
And second one is...
For this use UITableViewCell and design that cell.
This is second approach.

UIButton not working in UITableview

Have UITableviewcell --> inside which i have 4 different UIView and 3 of the views has UIButtons. I want to make UIButton clickable. For the first time the buttons are clickable but when i go to next screen and come back, the buttons don't work. Please let me know how to implement this? Thanks!
PHMyTripView *tripsView=[[PHMyTripView alloc] initWithFrame:CGRectMake(10, 5, self.frame.size.width-20, cell.frame.size.height)];
tripsView.onBaggageClick = ^{
[weakSelf handleBaggagePurchaseTapped];
};
if ([data count]>0) {
[tripsView fillTripData:[data firstObject]];
[tripsView showAncillaries:self.predictiveManager.upcomingCDAirBookingInfo];
}
[cell bringSubviewToFront:tripsView.bagsButton];
[cell.viewPlaceHolder addSubview:tripsView];
This happens because the cells are reusable and if you go to another screen the button may kinda mess round into different cell in UI or functionally.
The way to solve this is to add tag. You can define cell.tag = indexPath.row * 10 or so.
Then when draw the button, you check the condition, if cell.tag == ?, then add your button.
Thank you everyone for your response but they din't work in my case.
Here is the answer. Since the UITableview was reloading when it comes back to the screen.The frames were mis placed and Hence the button was not able to click.
Used this one line code which worked fine.
self.tripsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
You should turn off delaysContentTouches on each UITableView subview, which is an instance of UIScrollView class.
Subclass UITableView and override initWithFrame method:
.h file
#interface NoDelaysOnTouchTableView : UITableView
#end
And .m file
#import "NoDelaysOnTouchTableView.h"
#implementation NoDelaysOnTouchTableView
- (id) initWithFrame: (CGRect) frame
{
self = [super initWithFrame: frame];
if (self) {
for (id view in self.subviews) {
if ([NSStringFromClass([view class]) isEqualToString: #"UITableViewWrapperView"]) {
if ([view isKindOfClass: [UIScrollView class]]) {
// turn OFF delaysContentTouches in the hidden subview
UIScrollView* scroll = (UIScrollView*)view;
scroll.delaysContentTouches = NO;
}
break;
}
}
}
return self;
}
#end
Next - use this subclass (create an instance of NoDelaysOnTouchTableView) to be able to press UIButton immediately.
I think that the causes would be multiples.
You can try:
check the constraints for each button in your cell
in cellForRow you can do addTarget: for each button with relative #selector and in this method check the object (datasource) associated to button.
do not use addSubView in your cell, instead use a Xib (or define your cell in a storyboard within tableView) so you can set the constraints.
I Hope, i've helped you.
Not specifically about this issue, but for some people it may be the case.Try to add subviews in contentView of the cell.
Instead of addSubview(textField) use contentView.addSubview(textField)

Having a UIButton be tapped in a UICollectionViewCell

I have a UICollectionView with its cells all laid out.
I have this declared as a subview:
#property (nonatomic, strong) UIButton *aButton;
I then have that declared in each cell like so:
if (_aButton == nil)
{
_aButton = [UIButton buttonWithType:UIButtonTypeSystem];
}
// Add in all _aButton info here
[self.contentView addSubview:_aButton];
// Call to button pressed for button
[_aButton addTarget:self action:#selector(aButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
The button click method is like so:
- (IBAction) aButtonPressed:(UIButton *) sender
{
// Code never gets heree
}
The if(_aButton== `nil) is needed since cells get reused.
How do I make this work now? Thanks.
Add button action code before button added to view.... May be it will work .
// Call to button pressed for button
[_aButton addTarget:self action:#selector(aButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// Add in all _aButton info here
[self.contentView addSubview:_aButton];
I think, the way you are initializing the button is going to give you frame as 0,0,0,0 . So first give it a proper frame and title to be visible on the screen.
Then try tapping on that title and see if it works or not.
It's unclear what you trying to achieve here, but the button is not working because you not setting it's position and size on the cell. It could be done by setting frame or layout constraints.
Try to set button frame:
_aButton.frame = CGRectMake(0.0f, 0.0f, 50.0f, 50.0f);
You can also set background color for the button, just to make it visible on the cell:
_aButton.backgroundColor = [UIColor redColor];
Everything else is correct, button should work.

UIButton not clickable outside initial frame of an UIScrollView

I got stuck with the strange behavior of UIScrollView that I cannot click on the UIButton after I enlarge the contentSize of the UIScrollView.
What I wanted to do:
Show a form with using UIScrollView
After clicking on the submit button, the scroll view will enlarge some amount of height to show further information.
In the further information, I will place and show another UIButton(hidden at the beginning) in order to process to the next step.
The problem is that I placed the new UIButton to the enlarged area and the button is not clickable whereas I placed the UIButton to existing area(the initial frame of scroll view) then the button works normally. For both cases, the scroll bar of the scroll view performs normal behavior.(ie, the scroll end is the new content height)
Here is what I have so far:
A UIView xib (placed all elements inside it including the hidden button)
A UIScrollView (loaded the UIView xib into it)
UIView* view = [[[NSBundle mainBundle] loadNibNamed:#"view" owner:self options:nil] objectAtIndex:0];
[view loaded];
[scrollView addSubview:view];
After the submit button is clicked:
// offset = some amount;
[scrollview setContentSize:CGSizeMake(scrollview.contentSize.width, scrollview.contentSize.height+offset)];
// h = some amount before the end of the scroll view
CGRect r = nextBtn.frame;
r.origin.y = h;
nextBtn.frame = r;
[nextBtn setHidden:NO];
I have tried to change the clipSubviews attribute of scroll view but seems it is not working for my case at all.
Anyone knows how it happens? And is there any better methods to get this job done? (resize the scroll view and then place another button in it)
Any help would be great! Thanks a lot!
I assume that the button is direct or indirect child of the contents view you load from the xib file.
The problem is because you changed the scroll view's contentSize but did not change the frame of the contents view. Superviews participate in touch hit testing. You can place a subview outside of its superview bounds and by default the subview will not be clipped but touch events will not be delivered to it because the superview checks during hit testing that the touch is outside of its bounds and rejects the touch. See UIView hitTest:withEvent: for details.
You can add a button say submit and another button as subview of the scrollview.Keep your another button hidden in start and call setContentsize. now when user clicks on submit button then set another button to visible and again call set content size.In this way you would be able to achieve what you want to.
i have tried to generate scenario for you.I have tried this on view based application with storyboard without auto layout.
so in story board do some thing like this:
#import <UIKit/UIKit.h>
#interface ALViewController : UIViewController
#property (nonatomic, weak) IBOutlet UIScrollView *scroll;
#property (nonatomic, weak) IBOutlet UIButton *btn1;
#property (nonatomic, weak) IBOutlet UIButton *btn2;
===========
implementation:
#import "ALViewController.h"
#interface ALViewController ()
#end
#implementation ALViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.btn2 setHidden:YES];
[self adjustContentSize];
}
-(void)adjustContentSize
{
CGRect contentRect = CGRectZero;
for (UIView *view in self.scroll.subviews)
{
if (![view isHidden]) {
contentRect = CGRectUnion(contentRect, view.frame);
}
}
self.scroll.contentSize = contentRect.size;
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)btnClicked:(id)sender
{
UIButton *btn = (UIButton *)sender;
if (btn.tag ==1)
{
[self.btn2 setHidden:FALSE];
[self adjustContentSize];
}
}
#end
and in storyboard some thing like this:
#end
for your information:view frame 0,0,768,1024
scroll frame: 0,0,768,1024
btn1 frame: 361, 753, 46, 30
btn2 frame: 351, 1032, 46, 30
run your code :
at first your scroll view would be unscrollable because we have set btw 2 to be hidden and set content size.As soon as you will be clicking on btn 1, see code we are making btn 2 visible again and calling set content size.
Conclusion:
the scrollview content size looks for its visible contain of which we can take benefit of.
thanks and regards.

Move a programmatically generated button

I have a programmatically created button and I want to move it to a different location when a specific method is called. So far I can see the button I created, and I can move a different button that I drag-dropped into storyboard, but I am not sure how I can refer to the programmatically generated button in my code to change its location.
Code for generating button:
UIButton *generatedButton = [UIButton buttonWithType:UIButtonTypeCustom];
[generatedButton addTarget:self
action:#selector(genButtonTouched:)
forControlEvents:UIControlEventTouchDown];
generatedButton.frame = CGRectMake(84.0, 80.0, 70.0, 40.0);
[self.view addSubview:generatedButton];
Inside another method, I have code for changing a button's location. If this code is in the same method as where I generate the button it works fine, but I need to place this in a different method:
[generatedButton setFrame:CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)];
In your ButtonViewController.h
#interface ButtonViewController : UIViewController{
}
#property (retain, nonatomic) UIButton *generatedButton;
In your ButtonViewController.m
#implementation ButtonViewController
#synthesize generatedButton;
- (void)viewDidLoad
{
generatedButton = [UIButton buttonWithType:UIButtonTypeCustom];
[generatedButton addTarget:self
action:#selector(genButtonTouched:)
forControlEvents:UIControlEventTouchDown];
generatedButton.frame = CGRectMake(84.0, 80.0, 70.0, 40.0);
[self.view addSubview:generatedButton];
}
// to call the button anywhere within the class, do like this :-
-(void)methodToMoveButton{
[generatedButton setFrame:CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)];
}
If you want something else, please let me know.
It's no different than moving the button added in the storyboard. Create an instance variable to hold a reference to your generated button. Then you can access the button in the other method using that instance variable.

Resources