subviews with UIButtons - how to connect the buttons to IBActions - uibutton

I am trying to create a simple app which uses a main view and has a smaller subview within it. I need to have buttons in the subview and I am having trouble getting the connections for the buttons to work. I have done the following:
Create a new View-based project, which gave me the ViewController.h & .m, the MainStoryboard.storyboard and the AppDelegate.h & .m.
Create the subView using NewFile - Objective-C Class - then naming it "subView1" and making it a subclass of UIViewController and checking the with xib check box.
This gave me the subView1.h &.m files and the subView1.xib.
I then re-sized the subView in the xib, by setting it's size to "FreeForm" in the attributes inspector and then specifying the width (to 280) and height (to 300) in the size inspector. I also change the background colour to differentiate it from the main view.
I then dragged a UIButton into the subView and connected it as an IBAction (which i named "clickButton1") to the subView1.h file using touchupinside.
For testing purposes only i then used a simple NSLog to check the functionality of the button which i placed in the subView.m file as follows:
-(IBAction)clickButton1:(id)sender {
NSLog(#"It Worked!");
}
In my ViewController.m file in the viewDidLoad i then added the following code to add the subview to the main view:
subView1 *sv1 = [[subView1 alloc]init];
sv1.view.frame = CGRectMake(20,120,280,300);
[self.view addSubview: sv1.view];
This all worked fine, and when i run the app i get the main view and the subview appear as expected. The problem is when i click on the button which is located in the subview it crashes with the following error:
Thread1:EXC_BAD_ACCESS(code=1, address=0xe00000008)
From what i have read i believe this may have something to do with how I am adding the subview and the fact that I am using ARC. Something about once the subview is added it is automatically released and therefore all buttons/connections etc within the subview are lost.
So my two questions are 1) Am i missing something silly here and is there an easy fix? and 2) Is this an appropriate way to create an app which uses subviews with buttons within them or is there a better way? Thanks to anyone who takes the time to answer!

I tried to reiterate what you said.
So you first made a View-Based Application (checking the "Use Storyboards" checkbox), and you put a button in the storyboard. Then, you control-dragged the button to the "ViewController.h" file. If that is right, you should just be able to put
NSLog(#"It Worked!");
in the method implementation (at least, I could do that)

Related

iOS9 - UITableViewCellContentView is covering up Controls inside Cell

I have made a custom UITableViewCell called "SwitchCell" that has a switch.
In iOS9 Only, using Xcode 7 beta, the Content view in the cell is on top of the switch. (See screenshot of View Hierarchy. You can clearly see that the content view of the cell is on top of the other views. ):
So all the touches to the UISwitch are intercepted, and the IBAction does not fire.
In iOS8, this is not a problem. See screenshot for iOS 8.4 simulator. You can see that there is no content view on top of the controls:
Has anyone had this problem?
I tried remaking the NIB from scratch, but the same result occurs.
My NIB is a freeform size view with No status bar. It has two outlets: one for UILabel, one for UISwitch.
EDIT: please make sure to check the answer below that asks to verify that the cell's root view is not just a UIView but a UITableViewCell. This issue may also be a side effect of this.
After more investigation and searching, i found my solution here:
Button in UITableViewCell not responding under ios 7
What fixed it for me was:
cell.contentView.userInteractionEnabled = NO;
This prevents the cell content view from taking over the touch events, even though it's on top of the other views.
This issue was not only happening on iOS9, but on iOS7 as well. In iOS8, the Content view was behind the controls.
Problem can be in .xib file for your cell. When you create cell in separate .xib, be sure to drag UITableViewCell on canvas, not UIView.
SWIFT
I had an issue where my buttons in my custom tableviewcell swift files were working just fine, but then I upgraded to Xcode 12 and then all of a sudden I couldn't access them anymore (meaning my taps were not being recognized). The cell content view seemed to be interfering in the hierarchy and this like saved me:
cell.contentView.isUserInteractionEnabled = false
I put the line in cellForRowAt.
Thank you to #FranticRock
I had this problem when I was reusing a cell as a .xib. I didn't realise but when I first created the xib the default view that it created was in fact a UIView and not a UITableViewCell. It seems that at some stage UIKit adds the content view on top of my other elements and therefore interrupts certain events (e.g. touch events).
I resolved this by opening my xib file and dragging a UITableViewCell onto the canvas and copying my UI elements from the old view to the new cell.
Afterwards, additional settings also became available in the attributes inspector that matched those for a UITableViewCell.

Change a button's background image programmatically in cocoa

All of the topics that I have searched are outdated or not complete in Obj-c.
I need to learn how to change a button's background image programmatically, when having the actual button in the InterfaceBuilder. (This sounds odd, but I need it for NSCollectionView as I have many similar button with different background images).
In the interface builder I drag a button onto my view window, what should I do after?
I understand that:
I need to create a NSButton Class
Connect the button from the interface builder to the code
Set the image
I have been struggling with this.
So did you connect the button to an IBOutlet property? If so then all you need to do is use [button setImage:]
If you haven't already done so, make sure the object instance that you want to change the image from is in interface builder, I.e has been dropped in as one of those blue boxes. Then if you set the object's class and have an IBOutlet property in the header file you can just drag the button outlet in the outlets tab (looks like an arrow) to the actual button itself to link the two
Edit: So it appears you're having trouble with the actual connecting part of the button? Chances are your IB file looks a bit like this:
Look for the objects section in the left hand list. These are the actual objects in your code that you can connect your button to. You might see an app delegate object there, which is included in the default IB file generated when you first create a project. If you want to handle the image changing in your app delegate, then simply add this property to your AppDelegate.h file to create an outlet:
#property IBOutlet NSButton *button;
If you go back to interface builder and select the app delegate object, you can see the outlet that you just created under the outlet tab:
Drag the little circle thing to the button to connect it, that should be the easiest bit.
But I'm going to just presume that you want to call it from somewhere else other than your app delegate, and for that we'll need to do some more explaining. If the class you want to call it from is a subclass of NSView and is already in your interface builder, you can just add that line to your view's header file and it will appear under the view's outlet tab.
If you want to call this from another object that isn't a view or such, you'll need to do either two options:
Create the object instance in interface builder. This means that instead of creating in normally with alloc] init]; etc. you'll have to actually drag in an object into interface builder. This can change the structure of your object quite a bit as you'll no longer be able to create it at will, since it will automatically be instantiated whenever you load your .nib file. Also important to note is that your init function will not be called anymore and you'll need to use awakeFromNib instead. If you do choose to go down this route, just drag over an object:
Add your outlet property to the header file:
Set the object's class:
And connect the outlet:
If making objects XIB loaded just isn't your thing, you can always just connect the property outlet to your app delegate/view controller and access it from that instead. Hopefully this clears things up, if this was the problem you were having.
For iOS:
Don't need to create a NSButton subclass.
You only need to add button on Storyboard, set the IBOutlet property for your button (ctr+drag from your button to your view controller), and set the background image with:
[myButton setBackgroundImage:[UIImage imageNamed:#"ImageName"] forState:UIControlStateNormal]
For MacOS:
You can use
setImage:
as describe on Apple Doc, and changes its size/position
(Sorry for my bad English)
ofcourse as Duukee Said,i think no need to create any NSButton Or UIButton Instances Manually When We have an object in Interface Builder,We can just use it's outlet as follows,
UIImage* Desired_Image=[UIImage imageNamed:#"yourimage.png"];
[My_Button setimage:Desired_Image forState:UIcontrolstateNormal];
HTH!Happy Coding :)

Create a standalone view in storyboard to use programmatically

I'm trying to create and design a UIView using a storyboard but include it in a UIActionSheet programmatically. This is basically to avoid using CoreGraphics positioning functions with pixels
In old xcode I remember that it was possible to drag a UIView onto the nib without any controllers.
The view obviously has to be connected to the class, so it would have an IBOutlet, but not being added to the self.view
One thing that makes me feel like this should be possible is that if you drag a UIView into the controller black bar in storyboard it pops into place like so:
But its not shown on the screen itself. What is this feature for? Can I somehow open up this view and design it a bit?
Just create a new .xib file.
Right Click somewhere in the Navigator Area and select 'New File...'.
Select 'User Interface' from the list on the right and Select 'View'.
Click 'Next', 'Next', give your new view a name, and 'Create'.
A new .xib fill will be added to your project.
Double clicking on the new .xib file and it opens in Interface Builder (not Storyboard).
Edit/Design your View to your liking.
Then after you have your new view (.xib) in Interface Builder, it's a simple matter of creating a new subclass of UIView (ex. MyView), switching the class of your new view (.xib) to MyView, creating an instance of MyView in your controller, and adding it as a subview to your other view.
*And to answer your question about that little black bar at the bottom, it's called the 'Dock', and it's just a mini representation of the top-level documents of your scene. The dock is convenient for quickly dragging/dropping icons onto and making connections. See apple's storyboard description here. Ray Wenderlich has an easy to follow tutorial on storyboards here.
You cannot have a UIView outside of a UIViewController on a storyboard. I'm guessing it's because the storyboard would have no idea how to identify or instantiate with the current API. It is something I've had a use for myself. The solution is just use a XIB for the one UIView and load it up programmatically (just like used to do). I've found using a storyboard for most items and couple XIBs for re-usable views across multiple view controllers do work nicely together.
Here is some code I use to load a XIB as part of a custom object with the object gets initialized.
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[[[NSBundle mainBundle] loadNibNamed:#"BannerView" owner:self options:nil] objectAtIndex:0];
[self addSubview:self.view];
self.frame = self.view.frame;
}
return self;
}
As for dragging views down into the black bar on the storyboards. Those views are still part of the UIViewController, but they aren't a `subview' of the top level view. I think the document outline shows the hierarchy nicely.
The following view has 2.1.1 View, 2.1.2 View, etc outside of my main view hierarchy because they aren't subviews of my main view. The result is, they won't be displayed by default. I do have IBOutlets setup and I conditionally add/remove them from my main view hierarchy using the standard addSubview: and removeFromSuperview.

Combined UITableView with other elements - how to create and use the view?

Ive a project close to doing everything I need it to do. Its got a Main page which has four buttons that allow you to choose an option. Then a tableview page is launched from those options and displays a parsed XML feed from a website. You can then select one of the options in the table to see a detail view of the item, enquire about it, etc.
My problem is I need to add more elements to the TableViewController page, other than the tableview itself. I want a customized back button (not the navigation controller standard) plus some labels, images, etc.
In the TableViewController xib, the tableview itself fills the page. I cant resize it to add more elements above it. I can add a 'view' window seemingly above the tableview and put things in it. But it seems to add the view to the tableview. This means that when I scroll the table, the other elements like new back button, scroll away as part of the table.
So I'm led to wonder whether I need this page not to be a tableviewcontroller, but a viewcontroller, with a tableview inside it, as well as my other view with buttons, etc. Is that the right way to go? But if thats the case, then how do I instantiate the tableviewcontroller within code? Because my page will not be of that type anymore - it will be just a viewcontroller. But in code Im making a tableviewcontroller .. slightly scared by that route tbh.
Any illumination on this would be much appreciated, as various searches have left me none the wiser. Thanks.
To customize it, this is the way to go:
Change your class to be a view controller instead, which implements the TableViewDelegate and TableViewData Source protocols.
In the view didLoad of you controller, create the table view, set its delegate, data source, and any other properties you wish and add it as a subview to your view.
tableView = [[[UITableView alloc] init] autorelease];
tableView.delegate = self;
tableView.dataSource = self;
// .. Other customization
[self.view addSubview:tableView];
I suggest doing this programatically rather than IB.
Instead of a UITableViewController, you want a UIViewController that has an IBOutlet UITableView. Drag and drop a UITableView component from Storyboard and hook it up, and position it as needed on the screen. This UIViewController should implement the UITableViewDelegate and UITableViewDataSource methods.
Edit: Remember that a UITableViewController is just a subclass of UIViewController so you don't really have to get rid of all your code. :) You only need to make minor tweaks to your header and main file, and change the Storyboard to be a UIViewController instead of UITableViewController as I mentioned above.

ios change background on button click

I so far only have the interface builder layout
I'm not clear on the syntax to reference all of these items from the layout
I know that IBOutlet has to be used somewhere, but I need a bit more handholding on what this objective C is doing. Nothing I've read tells me exactly why some declarations start with + and others with -
What I want to do is click a button in my layout, have a modal view pop up and change the background on the entire layout.
so the first step is referencing all these items I've made in the nib. help? (or post a link to more intuitive tutorials that you know about)
So you probably want to create an IBOutlet for your background view. Maybe it's a UIImageView that you can set it's image property based on what the user selects in the modal view. For this you would just declare the UIImageView you have in your IB file
UIImageView *imageView;
and then declare it as a property
#property (nonatomic,retain)IBOutlet UIImageView *imageView;
and synthesize it in your .m file
#synthesize imageView;
Don't forget to release it if you're not using ARC.
Then you can open up interface builder and if you click on your view controller File's Owner and go to the connections inspector you will see there is a new connection there for imageView. Just drag that connection over to your UIImageView in the IB file and that's it. You now have a reference in your code that connects to your UIImageView in IB.
That will allow you to set the UIImageView in your code by typing something like
self.imageView.image = [UIImage imageNamed:theNameTheUserJustPicked];
In order to get the modal view, you need an IBAction to trigger a method in your code so declare one like this in your .h file of your main nib.
- (IBAction)displayViewBackgroundChooser;
and then define it in your .m file.
- (IBAction)displayViewBackgroundChooser {
//present your new view on screen here
}
Then go back to interface builder and click on the File's Owner again. You should see it there in the connections inspector and then you can connect it to a button, for example, that would trigger that method.
Hope this helps to clear things up a bit on IBOutlets and IBActions.
You can make your UI elements created in IB interact with your code by means of IBOutlets and IBActions.
In your case, I would associate an action to the button, so that it is fired when the button is clicked; the action would open a modal view, and you could change the background of that view in the viewDidLoad method of the associated controller.
Here you find a video tutorial about adding an outlet. And here, the same about actions.
About your doubt on + and -, - identifies a normal method defined in a class; + defines a class method, i.e., a method that you can call on the class directly, without having to instantiate it first. Have a look at this S.O. article for more.