thumbtackthief
thumbtackthief

Reputation: 6221

How do you hook up a custom UIView?

Writing my first iphone app through this tutorial--I have a custom UIView with the method showDie and I have two UIView elements on my storyboard that I've hooked up to my ViewController. However, both the UIView elements have the error message "No visible @interface for 'UIView' declares the selector 'showDie'. I think that's because the UIViews aren't subclassing XYZDieView, but when I control-clicked from my Storyboard, only UIView appeared in the dropdown--no XYZDieView. I tried just changing the text manually in the ViewController.h, but that didn't work (I didn't think it would). Am I on the right track? How do I use my subclass? (xcode 5)

XYZDieView.m

-(void)showDie:(int)num
{
    if (self.dieImage == nil){
        self.dieImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
        [self addSubview:self.dieImage];
    }
    NSString *fileName = [NSString stringWithFormat:@"dice%d.png", num];

    self.dieImage.image = [UIImage imageNamed:fileName];
}

XYZViewController.h

#import <UIKit/UIKit.h>
#import "XYZDieView.h"

@interface XYZViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *sumLabel;
@property (strong, nonatomic) IBOutlet UIButton *rollButton;

@property (strong, nonatomic) IBOutlet UIView *leftDieView;
@property (strong, nonatomic) IBOutlet UIView *rightDieView;

@end

XYZViewController.m

#import "XYZViewController.h"
#import "XYZDiceDataController.h"

@interface XYZViewController ()

@end

@implementation XYZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)rollButtonClicked:(UIButton *)sender {

    XYZDiceDataController *diceDataController = [[XYZDiceDataController alloc] init];
    int roll = [diceDataController getDiceRoll];
    int roll2 = [diceDataController getDiceRoll];

    [self.leftDieView showDie:roll];
    [self.rightDieView showDie:roll2];

    int sum = roll + roll2;

    NSString *sumText = [NSString stringWithFormat:@"Sum is %i", sum];
    self.sumLabel.text = sumText;
}

@end

Upvotes: 0

Views: 256

Answers (1)

Literphor
Literphor

Reputation: 498

Yes you're right, the problem is subclassing. In order to have a view conform to a subclass in the interface builder you need to

  1. Click on the UIView in your storyboard
  2. Open the right inspector panel
  3. Click on the third tab for identity inspector
  4. Add your class

Then try to connect it to your ViewController again.

Edit: Afterwards you may need to cast XYZDieView myView = (XYZDieView*)leftDieView;

Upvotes: 1

Related Questions