Having a UIButton be tapped in a UICollectionViewCell - ios

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.

Related

UIButton center position doesn't update with rotation

I have a program that dynamically generates UIButtons in the center of
the screen with push of another button.
The buttons are not updating the x-coordinates when I rotate the device.
Here is my code for creating buttons:
- (IBAction)createButton:(UIButton *)sender {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor redColor]];
[button addTarget:self action:#selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(self.xCoord,self.yOffset,100.0,120.0);
[self.view addSubview:button];
_yOffset = _yOffset+130;
}
The XCoord and self.yOffset were set in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.yOffset = 109;
self.xCoord = self.view.bounds.size.width/2-50;
}
The coordinates of the button in your code are fixed once they've been added to the view. If you want to update the frame of the buttons when the screen rotates, you'll need to trigger the repositioning of the buttons when the screen rotates.
AutoLayout in a storyboard makes this easier (if you just want a button to appear then you can add it in a storyboard and change its hidden property from NO to YES when the other button is pressed -- this won't be helpful if you want to add an arbitrary number of buttons, although you could have a hidden placeholder view that you use as a positioning reference)
If you want to keep the buttons x-position, you need to add Auto Layout constraints. There are a couple ways to do this programmatically. You can use the NSLayoutConstraint object directly or use Auto Layout's Visual Format Language. For more info, see Apple's documentation.

Displaying UIButton programmatically

I'm trying to display a button to the view programmatically with this code:
- (void)viewDidLoad {
_detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
_detailButton.frame = CGRectMake(23, 294, 72, 37);
[_detailButton setTitle:#"UIButton!" forState:UIControlStateNormal];
[_detailButton addTarget:self
action:#selector(showPop:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_detailButton];
}
I have the button declared in the .h file like this:
#property (strong, nonatomic) UIButton *detailButton;
The code does not throw any errors or warnings, but when I run there is no button displayed.
I check your code in my project its working fine i think in your case there are some other view that cover this button so check that your code has no problem at all.
Your button probably covered by another view. Just make sure its on top of other views.
In viewWillAppear add the following line of code:
[self.view bringSubviewToFront:self.detailButton];
If your button's type is of UIButtonTypeCustom, the button's default title color is white, so you can't see it if your view's background color is white.
[_detailButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

UIButton not highlighting when it is dynamically created

I have a dynamically created UIButton in my table's cellForRowAtIndexPath: method. It loads fine, and it can be selected, but it doesn't do the highlight animation when it is selected. I tried adding:
if(commandButton.isHighlighted), and that didn't trigger when selected. Here's how I load the cell:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* CellIdentifier=#"CommandCell";
UITableViewCell* commandCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];
[commandButton setTitle:#"Title" forState:UIControlStateNormal];
[commandCell.contentView addSubview:commandButton];
commandButton.backgroundColor = [UIColor blackColor];
return commandCell;
}
Whenever I click on it, commandButton is not highlighted...
EDIT: it was a stupid problem, I wasn't holding down my mouse for long enough. For those of you who have a similar problem, simply press down on the button for longer in the iOS simulator.
may this help you add the bellow code into ur code
if you want to so some image on tuchupinside then below code.
[commandButton setBackgroundImage:/*add you image using UIImage*/forState: UIControlStateHighlighted];
if you want simple (default background color when it appear in button on tuchupinside).
UIButton *buttonTap=[UIButton buttonWithType:UIButtonTypeRoundedRect];
and set the frame like this
buttonTap.frame=commandCell.frame;
//make some adjustment as per requied.
if u want some blur type effect(semi partial on selection )
Then you go for
UIButtonTypeCustom //type
The UIButton that you create in the following line
UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];
is a custom styled UIButton by default. For this button, you will have to set all the properties manually. What you want is this:
UIButton *commandButton = [UIButton buttonWithType:UIButtonTypeSystem];
[commandButton setFrame:cell.frame];
The UIButtonTypeSystem contains the style that you are looking for.
Hope this helps!
I don't know where are using this ? but still my suggestion is to give a tag to the button if you are adding it to the cell like :
UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];
[commandButton setTitle:#"Title" forState:UIControlStateNormal];
commandButton.tag = 1;
[commandCell addSubview:commandButton];
commandButton.backgroundColor = [UIColor blackColor];
and while accessing the same button ;
//you have to get the cell where button has been clicked
UIButton *button =(UIButton *)[cell viewWithTag:1];
and on this button you can use :
if(commandButton.isHighlighted)
Before you add button to cell view, try to add:
NSArray * views = [commandCell.contentView subviews];
for (UIView *object in views) {
[object removeFromSuperview ];
}
Because maybe u have multiple cells one on other, so the button is actually clicked is the "most bottom cell view" button.

Programmatically adding a view with a button

I want to add a view and a button programmatically like follows.
The problem is that the button does not react on clicking. I mean neither does it get highlighted or calls the selector.
The reason is that I want to implement a list row for a recording (a sound file). The list row should be selectable for drill-down and have a play button. So I got a RecordingView subclassing UIView that itself adds the button using a target from the constructor. See code below.
If anyone has a better approach to do this that could also be a solution.
#implementation MyViewController
- (IBAction) myAction {
RecordingView *recordingView = [[RecordingView alloc] initWithFrame:CGRectMake(30, 400, 130, 50)withTarget:self];
[recordingView setUserInteractionEnabled:YES];
[[self view] addSubview:recordingView];
}
#implementation RecordingView
- (id)initWithFrame:(CGRect)frame withTarget:(id) target
{
self = [super initWithFrame:frame];
UIButton *playButton = [[UIButton alloc] initWithFrame:CGRectMake(185, 5, 80, 40)];
[playButton setTitle:#"Play" forState:UIControlStateNormal];
[playButton setTitleColor:[UIColor darkTextColor]forState:UIControlStateNormal];
// creating images here ...
[playButton setBackgroundImage:imGray forState: UIControlStateNormal];
[playButton setBackgroundImage:imRed forState: UIControlStateHighlighted];
[playButton setEnabled:YES];
[playButton setUserInteractionEnabled:YES];
[playButton addTarget: target
action: #selector(buttonClicked:)
forControlEvents: UIControlEventTouchDown];
[self addSubview:playButton];
return self;
}
When I add the button the same way, directly in the view controller .m-file, the button does react on clicking. So there is something about the RecordingView. What do I need to do different here?
Also, are there any better ways to provide the target and selector for the touch event?
You may simply need to set userInteractionEnabled to YES on your RecordingView.
Another problem is that you are creating the RecordingView with a frame width of 130, but you are setting the X-axis origin of playButton to 185. This means playButton is entirely outside of the bounds of its superview. The default value for clipsToBounds is NO, so the button is drawn anyway. But touch events will never reach the button, because they are rejected when the system hit-tests the RecordingView.
This is from the hitTest:withEvent: documentation in UIView Class Reference:
Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. This can occur if the current view’s clipsToBounds property is set to NO and the affected subview extends beyond the view’s bounds.
You need to either make RecordingView's frame wider, or move playButton to be inside the bounds of its superview.

Clear button on UITextView

How can I add a clear button (cross inside a circle) for UITextView like UITextField has?
Based on the answer from GhostRider a more accurate and up to date implementation:
int kClearButtonWidth = 15;
int kClearButtonHeight = kClearButtonWidth;
//add the clear button
self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.clearButton setImage:[UIImage imageNamed:#"UITextFieldClearButton.png"] forState:UIControlStateNormal];
[self.clearButton setImage:[UIImage imageNamed:#"UITextFieldClearButtonPressed.png"] forState:UIControlStateHighlighted];
self.clearButton.frame = CGRectMake(0, 0, kClearButtonWidth, kClearButtonHeight);
self.clearButton.center = CGPointMake(self.textView.frame.size.width - kClearButtonWidth , kClearButtonHeight);
[self.clearButton addTarget:self action:#selector(clearTextView:) forControlEvents:UIControlEventTouchUpInside];
[self.textView addSubview:self.clearButton];
And the method
- (void)clearTextView:(id)sender{
self.textView.text = #"";
}
You can use this images for the two states of the button:
just make a uibutton and put it on uitextview and set its action for clear text view;
uitextview.frame = (0,0,320,416);
uibutton.frame = (310,0,10,10);
[uibutton setimage:#"cross.png" forcontrolstate:uicontrolstatenoraml];
[uibutton addTarget:self action:#selector(clearButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
-(void)clearButtonSelected{
uitextview=#"";
}
hope you want to clear the text view text when you click on cross button above is help
if not understand then i can send you proper program for that
From product perspective, if you're going to have a clear button, you probably want to use a UITextField instead of a UITextView and UITextField supports a clear button natively - set the clearButtonMode property as such:
UITextField *textfield = ...;
textfield.clearButtonMode = UITextFieldViewModeAlways;
See screenshot:
You could use UITextFieldViewModeWhileEditing to only present the clear button while the user is actively updating the content.
There's nothing built in like there is for the UITextField. You'd have to add the view yourself (probably a UIButton) and place it correctly and also somehow get the text to wrap around it correctly. (And I don't think the latter is really possible.)
Maybe instead you should display a toolbar above the keyboard (or an inputAccessoryView if you're targeting 3.2 and later) that provides a clear button.
For me changing the .frame or the .contentInset properties did not work.
For me the best result came from:
1) adding a UIView to the controller, give it round corners and a border to mimic a UITextView.
self.viewTextBackground.layer.borderColor = [UIColor colorWithRed:171/255.0 green:171/255.0 blue:171/255.0 alpha:1.0].CGColor;
self.viewTextBackground.layer.borderWidth = 1.0f;
self.viewTextBackground.layer.cornerRadius = 9.0f;
2) place UITextView on top of this UIView. Place it so that the borders of the underlying UIView stay visible.
3) give the UITextView round corners:
self.textNote.layer.cornerRadius = 9.0f;
3) Make its width fe. 30pixels less compared to the underlying UIView. You now have space for a clear-button.
4) simply add a UIButton to your controller and place it in the top-right corner of the underlying UIView.
5) change the buttons properties: set its type to 'custom' and set its image to the image of a grey cross.
6) bind an action to the button te clear the UITextView
You can add a clear button like the one in the attached screenshot with minimal coding. Just follow these steps:
Select the storyboard and drag a UIButton into your UITextView
Set the buttons constraints
Assign a title or a background image
Create the button's IBOutlet reference and the action (see onClearPressed(_:) below) for "Touch Up Inside" in the ViewController
Implement the textViewDidChange(_:) UITextViewDelegate delegate method, and make sure to set the button's isEnabled property based on the textfield content, e.g.:
func textViewDidChange(_ textView: UITextView) {
clearButton.isEnabled = !textView.text.isEmpty
}
Implement the onClearPressed(_:) action:
#IBAction func onClearPressed(_ sender: Any) {
textView.text = ""
clearButton.isEnabled = false
}
That's it.

Resources