I am trying to make a custom Xcode UIPicker with only numbers 1-10. Is there any simple way to do this with an Identity Inspector or if not, what is the best way to go about making this simple UIPicker?
Thanks in advance!
No, you can't create a picker using only Inerface Builder. There is no equivalent to UITableView Static cells for UIPicker. You need a view controller but it's not that complicated. The view controller need to implement the UIPickerViewDataSource, UIPickerViewDelegate delegates. Here is the basics for a single column picker with the values 1 to 10.
#import "ViewController.h"
#interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
#property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UIPickerView Data Source & Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return 10;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat:#"%d", row + 1 ];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// TODO do something with the selection
}
#end
To create a minimal iOS app with a picker. Create a new Project select single window application. Replace the code in ViewController.m with above. Edit the story board and add a picker. Important You need to connect the picker view in the storyboard to the IBOutlet in the code.
Not Connected
To connect the outlet you should be editing the storyboard in assistant editor mode. The assisted editor will display the code and the IBOutlet property. Now "Control Click the picker view in the storyboard and drag to the line of code declaring the IBOutlet. The connection is made when the circle is black in the gutter on the line declaring the IBOutlet property.
Connected
Xcode Editing Storyboard in Assistant Editor Mode
FYI: By far the best and fastest moving way to learn iOS is the Stanford iTunes U Course:
Developing iOS 7 Apps for iPhone and iPad
https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550
You will need to watch a few of the demos to grok how to make connections Interface Builder (IB). The first thing you need to understand is the IB does not create resource or configuration files. The storyboard files contain serialized interface objects. Almost identical to the objects you can create in code.
Changing the size of the picker text
You need to replace the implementation of pickerView:titleForRow:forComponent: with your own pickerView:rowHeightForComponent: and pickerView:viewForRow:forComponent:reusingView:
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 60; // Row height in points, Note this should match the height of the UILabel Rect.
}
// FYI points are not pixels on non retina screens 1 point = 1 pixel but on retina screens 1 point = 2 pixels
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
if (view) {
UILabel *reuseLabel = (UILabel *)view;
reuseLabel.text = [NSString stringWithFormat:#"%ld", row + 1 ];
return reuseLabel;
}
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
newLabel.text = [NSString stringWithFormat:#"%ld", row + 1 ];
newLabel.font = [UIFont systemFontOfSize:42];
newLabel.textAlignment = NSTextAlignmentCenter;
return newLabel;
}
Related
I have a dynamic NSTableView which can add a number of columns depending on the data provided. For each column I have set the header cell to be a NSPopUpButtonCell. (Side-note: I've had to use a custom subclass class for NSTableHeaderView otherwise the menu doesn't pop-up). All works well, apart from a duplicate or extra header button cell on the top right. It mirrors perfectly the previous column selection as shown in screenshots. My question is how do I stop the NSTableView from recycling the previous popup header cell? (By the way I have tried the setCornerView method but that only effects the header area above the vertical scrollbar.)
I came across the same problem this week. I went with the quick fix,
[_tableView sizeLastColumnToFit];
(However, after discussion with OP this requires that you use a subclass of NSPopUpButtonCell in the header and also NSTableHeaderView. I attach my solution below)
You can to this by combining the approaches outlined here,
PopUpTableHeaderCell
DataTableHeaderView
Here is a simplified snippet,
// PopUpTableHeaderCell.h
#import <Cocoa/Cocoa.h>
/* Credit: http://www.cocoabuilder.com/archive/cocoa/133285-placing-controls-inside-table-header-view-solution.html#133285 */
#interface PopUpTableHeaderCell : NSPopUpButtonCell
#property (strong) NSTableHeaderCell *tableHeaderCell; // Just used for drawing the background
#end
// PopUpTableHeaderCell.m
#implementation PopUpTableHeaderCell
- (id)init {
if (self = [super init]){
// Init our table header cell and set a blank title, ready for drawing
_tableHeaderCell = [[NSTableHeaderCell alloc] init];
[_tableHeaderCell setTitle:#""];
// Set up the popup cell attributes
[self setControlSize:NSMiniControlSize];
[self setArrowPosition:NSPopUpNoArrow];
[self setBordered:NO];
[self setBezeled:NO];
[self setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
}
return self;
}
// We do all drawing ourselves to make our popup cell look like a header cell
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView{
[_tableHeaderCell drawWithFrame:cellFrame inView:controlView];
// Now draw the text and image over the top
[self drawInteriorWithFrame:cellFrame inView:controlView];
}
#end
Now for the NSTableViewHeader subclass.
//DataTableHeaderView.h
#import <Cocoa/Cocoa.h>
/* Credit: http://forums.macnn.com/79/developer-center/304072/problem-of-nspopupbuttoncell-within-nstableheaderview/ */
#interface DataTableHeaderView : NSTableHeaderView
#end
//DataTableHeaderView.m
#import "DataTableHeaderView.h"
/* Credit: http://forums.macnn.com/79/developer-center/304072/problem-of-nspopupbuttoncell-within-nstableheaderview/ */
#implementation DataTableHeaderView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)mouseDown:(NSEvent *)theEvent {
// Figure which column, if any, was clicked
NSPoint clickedPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
NSInteger columnIndex = [self columnAtPoint:clickedPoint];
if (columnIndex < 0) {
return [super mouseDown:theEvent];
}
NSRect columnRect = [self headerRectOfColumn:columnIndex];
// I want to preserve column resizing. If you do not, remove this
if (![self mouse:clickedPoint inRect:NSInsetRect(columnRect, 3, 0)]) {
return [super mouseDown:theEvent];
}
// Now, pop the cell's menu
[[[self.tableView.tableColumns objectAtIndex:columnIndex] headerCell] performClickWithFrame:columnRect inView:self];
[self setNeedsDisplay:YES];
}
- (BOOL)isOpaque {
return NO;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
#end
You can tie everything together in the AppDelegate -awakeFromNib or similar,
-(void) awakeFromNib {
/* NB the NSTableHeaderView class is changed to be an DataTableHeaderView in IB! */
NSUInteger numberOfColumnsWanted = 5;
for (NSUInteger i=0; i<numberOfColumnsWanted; i++) {
PopUpTableHeaderCell *headerCell;
headerCell = [[PopUpTableHeaderCell alloc] init];
[headerCell addItemWithTitle:#"item 1"];
[headerCell addItemWithTitle:#"item 2"];
[headerCell addItemWithTitle:#"item 3"];
NSTableColumn *column;
[column setHeaderCell:headerCell];
[column sizeToFit];
[_tableView addTableColumn:column];
}
/* If we don't do this we get a final (space filling) column with an unclickable (dummy) header */
[_tableView sizeLastColumnToFit];
}
Other than that I haven't figured out how to properly correct the drawing in that region.
It seems like it's the image of the last cell that is being duplicated. So I slightly more hack-ish approach would be to add a extra column to your table view with a blank name and which intentionally ignores the mouse clicks. Hopefully by setting the display properties of the last column you can make it look the way you want.
I couldn't find any NSTableView or NSTableViewDelegate method that allow control of this region, so may any other solution would be very complicated. I would be interested in a nice solution too, but I hope this gets you started!
I have this issue and i don't use NSPopUpButtonCell at all.
I just want to tell about other method how to hide this odd header. This methods will not remove an odd table column, i.e. if you have 2 'legal' columns and hide this extra 3rd column header, you will still be able to move separator between 2nd and 3rd column. But in this case you won't see redundant header even if you want to resize any column.
I still need solution how to completely remove the redundant column, and why this is happening. (and why Apple won't fix this bug?)
So... you can just calculate index of column which this header belongs to and according to this draw your header or don't. First, subclass NSTableHeaderCell and set it as a cell class for columns. Let assume your subclass named TableHeaderCell:
for column in self.tableView.tableColumns {
let col:NSTableColumn = column as! NSTableColumn
//you can operate with header cells even for view-based tableView's
//although the documentation says otherwise.
col.headerCell = TableHeaderCell(textCell: col.title)
//or what initialiser you will have
}
Then in TableHeaderCell's drawWithFrame method you should have:
override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) {
let headerView = controlView as! HashTableHeaderView
let columnIndex = headerView.columnAtPoint(cellFrame.origin)
if columnIndex == -1 {
return
}
//parent's drawWithFrame or your own draw logic:
super.drawWithFrame(cellFrame, inView: controlView)
}
After this you won't have redundant header drawn because it not belongs to any column and columnAtPoint method will return -1.
How can one have checkboxes and textfield (for section headings) in a single tableview column using NSTableViewDataSource Protocol?
My requirement is to use a Cell Based TableView.
I answered your other question without any code and i think you had trouble understanding it.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
array = [[NSMutableArray alloc]initWithObjects:#0,#1,#2, nil];//instead this you can add your class object
[self.myTableView reloadData];
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
return [array count];
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
NSButtonCell * cell =[[NSButtonCell alloc]init];
[cell setButtonType:NSSwitchButton];
if([array objectAtIndex:row] == [NSNumber numberWithInt:0])
{
[tableColumn setDataCell:cell];
[[tableColumn dataCell]setTitle:#"Are you single?"];// instead this you can access title from your class object or from any other storage
}
else if ([array objectAtIndex:row] == [NSNumber numberWithInt:1])
{
[tableColumn setDataCell:[[NSTextFieldCell alloc]init]];
}
else if ([array objectAtIndex:row] == [NSNumber numberWithInt:2])
{
[tableColumn setDataCell:cell];
[[tableColumn dataCell]setTitle:#"Are you happy?"];
}
return [array objectAtIndex:row];
}
So thought this would help:) Cheers.
Here are the steps to make a single column tableview where the column can have row(s) that are section headings (NSTextFieldCells) followed by rows that are checkboxes (NSButtonCells) having descriptive titles. Similar to a listbox in MS MFC. To be compatible with older versions of OS X it needs to be a Cell based tableview:
Using IB drag a tableView control into the Application Window. In the Attributes inspector set Content Mode as "Cell Based", and Columns to 1.
Using IB drag a "Check Box Cell" control from the Object Library into the Application Window's column. (note: this step probably can be omitted since in the example code shown below, the cell type is being set explicitly to be either a NSButtonCell (checkbox) or NSTextFieldCell). If one needs to expand this example to use multiple columns, then probably want to set the Identifier for the NSTableColumn(s) in IB's Identity Inspector, in order that in the code one can filter by column/row instead of only by row (i.e. inside of the method objectValueForTableColumn).
Set the TableView's datasource and delegate to be the auto generated App Delegate object (in this case ApplicationAppDelegate.h). Do this by opening IB, and using the "Connection Inspector" click and drag from the datasource circle connection icon to the "App Delegate" object icon in the IB panel that shows objects that are loaded from the NIB such as controls, controllers etc.(icon for App Delegate is a blue cube). Do the same click and drag operation with the delegate circle icon.
Open the Assistant Editor, with the App Delegate's .h file showing in the left vertical pane and the IB view of the Table View in the right vertical pane. Select on the TableView control and create an IB outlet named "tableView" by holding the control key and dragging from the TableView Control to the section of the .h file where properties are listed.
Declare a NSMutableArray variable in the .h file. It should look like the following (Note: there has been added NSTableViewDataSource as a supported protocol of ApplicationAppDelegate):
#import <Cocoa/Cocoa.h>
#interface ApplicationAppDelegate : NSObject <NSApplicationDelegate,NSTableViewDataSource>
{
NSMutableArray *state;
}
#property (assign) IBOutlet NSWindow *window;
#property (weak) IBOutlet NSTableView *tableView;
#end
6 . Add the following functions to the App Delegate implementation file (.m):
#import "ApplicationAppDelegate.h"
#implementation ApplicationAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
state = [[NSMutableArray alloc]initWithObjects:#"Section Heading:",#0,#1, nil];//Note: values passed to NSButtonCells should be 0 or 1 or YES or NO, and the state passed to NSTextFieldCell is a NSString
[self.tableView reloadData];
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
return [state count];
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
NSButtonCell * cell =[[NSButtonCell alloc]init];
[cell setButtonType:NSSwitchButton];
if (row == 0)
{
[tableColumn setDataCell:[[NSTextFieldCell alloc]init]];
}
else if (row == 1)
{
[tableColumn setDataCell:cell];
[[tableColumn dataCell]setTitle:#"title row1"];
}
else if (row == 2)
{
[tableColumn setDataCell:cell];
[[tableColumn dataCell]setTitle:#"title row2"];
}
return [state objectAtIndex:row];
}
- (void)tableView:(NSTableView *)tableView setObjectValue:(id)value forTableColumn:(NSTableColumn *)column row:(NSInteger)row
{
[state replaceObjectAtIndex:row withObject:value];
[tableView reloadData];
}
#end
NSCollectionView remains one of the most mysterious parts of the Cocoa API that I've ever seen. Documentation is poor and there are many moving parts, many of which are often implemented in Interface Builder, making documentation challenging.
Please provide sample code to create the simplest case of NSCollectionView which displays either Text Fields or Buttons without using Xcode where each Text Field or Button has a different Title. Assume a new Xcode project with the default window IBOutlet.
For this example, no binding is required to update the NSCollectionView as the data source changes. Simply display a grid of prototype objects and set each object's Title to some value.
If we can get a good example of how to do this available to many people, I think it will help everyone who works with NSCollectionViews and is as baffled as I am.
Summary of request
Provide sample code to render an NSCollectionView in a new Xcode project
Do not use Interface Builder, do use the default window IBOutlet provided
NSCollectionView should contain Text Fields or Buttons, your choice
Each item in the view should have a different Title
No binding is required
If there's sample code out there that meets these requirements, please provide a link, that'd be great!
I’m not sure there’s much insight in creating a collection view programmatically and without bindings, but here it goes.
Introduction
There are essentially four components when using a collection view:
View: a subclass of NSView, responsible for displaying information;
The collection view itself;
View controller: a subclass of NSCollectionViewItem that serves as the collection view item prototype;
Model: an array of objects.
Usually a view is designed in Interface Builder, and a model is mediated by Cocoa bindings.
Doing it programmatically:
Constants
static const NSSize buttonSize = {80, 20};
static const NSSize itemSize = {100, 40};
static const NSPoint buttonOrigin = {10, 10};
View
This is a standard view (a custom view in Interface Builder parlance) containing a button. Note that the view has fixed size.
#interface BVView : NSView
#property (weak) NSButton *button;
#end
#implementation BVView
#synthesize button;
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:(NSRect){frameRect.origin, itemSize}];
if (self) {
NSButton *newButton = [[NSButton alloc]
initWithFrame:(NSRect){buttonOrigin, buttonSize}];
[self addSubview:newButton];
self.button = newButton;
}
return self;
}
#end
View Controller (Prototype)
Normally a view controller loads its view from a nib file. In the rare cases where the view controller doesn’t obtain its view from a nib file, the developer must either send it -setView: before -view is received by the view controller, or override -loadView. The following code does the latter.
View controllers receive the corresponding model object via -setRepresentedObject:. I’ve overridden it so as to update the button title whenever the model object changes. Note that this can be accomplished by using Cocoa bindings without any code at all.
Note that none of this code is specific to collection views — it’s general view controller behaviour.
#interface BVPrototype : NSCollectionViewItem
#end
#implementation BVPrototype
- (void)loadView {
[self setView:[[BVView alloc] initWithFrame:NSZeroRect]];
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
[[(BVView *)[self view] button] setTitle:representedObject];
}
#end
Model
A simple array of strings representing button titles:
#property (strong) NSArray *titles;
self.titles = [NSArray arrayWithObjects:#"Case", #"Molly", #"Armitage",
#"Hideo", #"The Finn", #"Maelcum", #"Wintermute", #"Neuromancer", nil];
Collection View
So far, the only relation that’s been established is the view (BVView) used by the item prototype (BVPrototype). The collection view must be informed of the prototype it should be using as well as the model from which to obtain data.
NSCollectionView *cv = [[NSCollectionView alloc]
initWithFrame:[[[self window] contentView] frame]];
[cv setItemPrototype:[BVPrototype new]];
[cv setContent:[self titles]];
Full Source Code for the Application Delegate
#import "BVAppDelegate.h"
static const NSSize buttonSize = { 80, 20 };
static const NSSize itemSize = { 100, 40 };
static const NSPoint buttonOrigin = { 10, 10 };
#interface BVView : NSView
#property (weak) NSButton *button;
#end
#implementation BVView
#synthesize button;
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:(NSRect){frameRect.origin, itemSize}];
if (self) {
NSButton *newButton = [[NSButton alloc]
initWithFrame:(NSRect){buttonOrigin, buttonSize}];
[self addSubview:newButton];
self.button = newButton;
}
return self;
}
#end
#interface BVPrototype : NSCollectionViewItem
#end
#implementation BVPrototype
- (void)loadView {
[self setView:[[BVView alloc] initWithFrame:NSZeroRect]];
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
[[(BVView *)[self view] button] setTitle:representedObject];
}
#end
#interface BVAppDelegate ()
#property (strong) NSArray *titles;
#end
#implementation BVAppDelegate
#synthesize window = _window;
#synthesize titles;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.titles = [NSArray arrayWithObjects:#"Case", #"Molly", #"Armitage",
#"Hideo", #"The Finn", #"Maelcum", #"Wintermute", #"Neuromancer", nil];
NSCollectionView *cv = [[NSCollectionView alloc]
initWithFrame:[[[self window] contentView] frame]];
[cv setItemPrototype:[BVPrototype new]];
[cv setContent:[self titles]];
[cv setAutoresizingMask:(NSViewMinXMargin
| NSViewWidthSizable
| NSViewMaxXMargin
| NSViewMinYMargin
| NSViewHeightSizable
| NSViewMaxYMargin)];
[[[self window] contentView] addSubview:cv];
}
#end
#Bavarious
You did an excellent job there. This was just an amazing tutorial which I sometimes miss at the Apple Docs.
I rewrote Bavarious' code in Swift (v2) for anyone who's interested:
// AppDelegate.swift:
import Cocoa
let buttonSize:NSSize = NSSize(width: 80, height: 20)
let itemSize:NSSize = NSSize(width: 100, height: 40)
let buttonOrigin:NSPoint = NSPoint(x: 10, y: 10)
let titles:[String] = ["Case", "Molly", "Armitage", "Hideo", "The Finn", "Maelcum", "Wintermute", "Neuromancer"]
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
let cv = NSCollectionView(frame: self.window.contentView!.frame)
cv.itemPrototype = BVTemplate()
cv.content = titles
cv.autoresizingMask = NSAutoresizingMaskOptions.ViewMinXMargin
.union(NSAutoresizingMaskOptions.ViewWidthSizable)
.union(NSAutoresizingMaskOptions.ViewMaxXMargin)
.union(NSAutoresizingMaskOptions.ViewMinYMargin)
.union(NSAutoresizingMaskOptions.ViewMaxYMargin)
.union(NSAutoresizingMaskOptions.ViewHeightSizable)
window.contentView!.addSubview(cv)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
// BVTemplate.swift:
import Cocoa
class BVTemplate: NSCollectionViewItem {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
override func loadView() {
print("loadingView")
self.view = BVView(frame: NSZeroRect)
}
override var representedObject:AnyObject? {
didSet {
if let representedString = representedObject as? String {
(self.view as! BVView).button?.title = representedString
}
}
}
}
// BVView.swift:
import Cocoa
class BVView: NSView {
var button:NSButton?
override init(frame frameRect: NSRect) {
super.init(frame: NSRect(origin: frameRect.origin, size: itemSize))
let newButton:NSButton = NSButton(frame: NSRect(origin: buttonOrigin, size: buttonSize))
self.addSubview(newButton)
self.button = newButton
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
To answer brigadir's question on how to bind to a mutable array.
zero'th - make titles an NSMutableArray
first - bind the array to your items
[cv bind:NSContentBinding
toObject:self
withKeyPath:#"titles"
options:NULL];
Second - when altering titles, make sure to modify the proxy.
e.g.
NSMutableArray *kvcTitles = [self mutableArrayValueForKey:#"titles"];
[kvcTitles removeLastObject];
I'm working on a game for the iPad, and I have it start up with a menu screen. For a while, the menu screen would come up just fine in the simulator. I'm using the main view controller that xcode provides when starting up a view-based application. But, unfortunately, I accidentally cut off the connection between the UIView and the view controller in interface builder, and after reconnecting it, the screen comes up as blank now. It works fine when I simulate the screen in interface builder, but not when running in xcode. Here's the code for the view controller:
//
// FunctionMachineViewController.h
// FunctionMachine
//
// Created by Kameron Schadt on 5/24/11.
// Copyright 2011 Willamette University. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface FunctionMachineViewController : UIViewController {
IBOutlet UITextField* equation;
IBOutlet UISlider* startLevel;
IBOutlet UITextView* startLevelNumber;
}
- (IBAction) startOnePlayer:(id)sender;
- (IBAction) startTwoPlayer:(id)sender startingEquation:(NSString*)equationUsed;
- (IBAction) sliderValueChanged:(UISlider*)sender;
#property(nonatomic, retain) IBOutlet UISlider* startLevel;
#property(nonatomic, retain) IBOutlet UITextField* equation;
#property(nonatomic, retain) IBOutlet UITextView* startLevelNumber;
#end
//
// FunctionMachineViewController.m
// FunctionMachine
//
// Created by Kameron Schadt on 5/24/11.
// Copyright 2011 Willamette University. All rights reserved.
//
#import "FunctionMachineViewController.h"
#import "GameViewController.h"
#implementation FunctionMachineViewController
#synthesize equation, startLevel, startLevelNumber;
- (IBAction)sliderValueChanged:(UISlider*)sender {
[startLevelNumber setText:[NSString stringWithFormat:#" %.1f", [sender value]]];
}
-(IBAction)startOnePlayer:(id)sender
{
GameViewController* GameView = [[GameViewController alloc] initWithNibName:nil bundle:nil];
[GameView isOnePlayer:YES];
[self presentModalViewController:GameView animated:YES];
}
-(IBAction)startTwoPlayer:(id)sender startingEquation:(NSString*)equationUsed
{
GameViewController* GameView = [[GameViewController alloc] initWithNibName:nil bundle:nil];
[GameView isOnePlayer:NO];
[self presentModalViewController:GameView animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
I didn't really see any problem here, so I'm assuming it has something to do with me reconnecting the view controller to the view. I don't have an actual view file that I'm using, just the viewcontroller. Can anybody help?
Check the setting of "Main nib file base name" in [YourApp]-info.plist, in the "Supporting Files" folder – if you've changed the name of your root view controller, you may need to change the name here as well.
For some odd reason my Referencing outlet for the App Delegate was disconnected.
Try creating a referencing outlet from delegate to File's Owner using the connections inspector (farthest right menu) for your App Delegate.
I've been searching all over the net for an answer to this one! Hoping one of you can help me.
So far I have a button that produces a random nr between 1 and 6 in a label.
Then I want a picture to appear depending on what nr is in the label.
For example: If the number 1 is generated, I want img1.png to appear in a UIImageView.(?)
I'm thinking maybe a if function to pick the picture?
Sorry for bad formating.
Here is the .h file:
#import <UIKit/UIKit.h>
#interface xxxViewController : UIViewController
{
IBOutlet UILabel *label;
int randomNumber;
}
-(IBAction)randomize;
#end
...and here is the .m file:
#import "xxxViewController.h"
#implementation xxxViewController
-(IBAction)randomize
{
int randomNumber = 1+ arc4random() %(6);
label .text = [NSString stringWithFormat:#"%d",randomNumber];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int randomNumber = 1+ arc4random() %(6);
label .text = [NSString stringWithFormat:#"%d",randomNumber];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
You can use the number to create the file name, for instance [NSString stringWithFormat:#"image%d.png", number];. It's probably a better practice (though not necessary for what you're doing) to create a list of file names, and associate them with numbers in an NSDictionary so you're always dealing with known image names.