ios - 如何连接自定义 UIView?

标签 ios iphone objective-c cocoa-touch uiview

通过本教程编写我的第一个 iphone 应用程序——我有一个带有方法 showDie 的自定义 UIView,我的 Storyboard上有两个 UIView 元素,我已将它们连接到我的 ViewController。但是,两个 UIView 元素都有错误消息“'UIView' 的可见 @interface 声明了选择器'showDie'。我认为那是因为 UIView 不是 XYZDieView 的子类,但是当我控制 -从我的 Storyboard 中单击,只有 UIView 出现在下拉列表中——没有 XYZDieView。我尝试在 ViewController.h 中手动更改文本,但这没有用(我认为它不会)。我是对的吗跟踪?我如何使用我的子类?(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

最佳答案

是的,你是对的,问题在于子类化。为了使 View 符合界面构建器中的子类,您需要

  1. 点击 Storyboard中的 UIView
  2. 打开右侧检查器面板
  3. 点击身份检查器的第三个选项卡
  4. 添加你的类(class)

然后尝试再次将其连接到您的 ViewController。

编辑:之后您可能需要转换 XYZDieView myView = (XYZDieView*)leftDieView;

关于ios - 如何连接自定义 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337095/

相关文章:

ios - 渐变不覆盖 iphone plus 设备上的图像 ios swift 3

iphone - UIButton事件“触摸保持”

objective-c - 比较数组中的字符串和另一个字符串

Objective-C 到 Swift 3 方法名称更改问题

ios - MFMailComposeViewController:取消按钮不可见

ios - UIRefreshControl 和 UiTableview 内容插图

ios - 在 objective-c 中本地或 firebase 录制后如何保存音频文件?

ios - Facebook 登录 iOS 10 一直有效,直到第二次按下按钮

ios - 在 TableView 单元格中显示多行 - IOS

iphone - 两个 View ,一个在纵向下方,横向并排使用布局约束