Добавление цели для UIButton добавлено в подкласс UIView, не работающий на UIViewController - PullRequest
2 голосов
/ 20 октября 2010

У меня есть пользовательский UIButton, добавленный как подвид к подклассу UIView.В моем viewController я добавляю пользовательский интерфейс в качестве подпредставления к представлению контроллера.Затем я пытаюсь добавить цель в uibutton (внутри viewWillLoad), но селектор никогда не вызывается.

Ответы [ 5 ]

1 голос
/ 14 января 2011

Мне просто нужно было переместить всю логику, которая была в layoutSubviews, в конструктор.

0 голосов
/ 07 июля 2014

Во-первых, UIView отличается от UIControl. UIView не знает конкретно, как рассматривать различные взаимодействия с пользователем и не реализует большую часть метода обработки событий.

UIControl сделает это за вас. Его известный подкласс UIButton. Попробуйте создать подкласс от UIControl, чтобы получить все методы для обработки событий. Для более сложного способа, внутри этого подкласса UIView подкласс другого UIControl, но я не думаю, что это хорошая идея.

Более продвинутая обработка событий и передача сообщений:

Как добавить UIViewController в качестве цели действия UIButton, созданного в программно созданном UIView?

0 голосов
/ 24 октября 2010

Вот пользовательский вид и логика контроллера вида

// пользовательский вид

@implementation CustomUIASView

@synthesize firstButton;
@synthesize secondButton;
@synthesize thirdButton;

- (id)initWithFrame:(CGRect)frame {

 if ((self = [super initWithFrame:frame])) {

  self.alpha           = .85;
  self.backgroundColor = [UIColor blackColor];
}

  return self;
}


- (void)layoutSubviews {

  UIImage *buttonImageNormal;
  UIImage *stretchableButtonImageNormal;
//
  buttonImageNormal            = [UIImage imageNamed:@"as-bg.png"];
  stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];

  self.firstButton = [UIButton buttonWithType:UIButtonTypeCustom];

  self.firstButton.frame           = CGRectMake(10, 10, 300, 50);
  self.firstButton.backgroundColor = [UIColor clearColor];

  [self.firstButton setTitleColor:RGB(16,62,30) forState:UIControlStateNormal];
  [self.firstButton setTitle:@"Watch Video" forState:UIControlStateNormal];
  [self.firstButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];

  self.firstButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];

  [self addSubview:self.firstButton];

  self.secondButton = [UIButton buttonWithType:UIButtonTypeCustom];

  self.secondButton.frame           = CGRectMake(10, (10 + 50 + 5), 300, 50);
  self.secondButton.backgroundColor = [UIColor clearColor];

  [self.secondButton setTitleColor:RGB(16,62,30) forState:UIControlStateNormal];
  [self.secondButton setTitle:@"Save to My Favorites" forState:UIControlStateNormal];
  [self.secondButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];

  self.secondButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];

  [self addSubview:self.secondButton];

  self.thirdButton = [UIButton buttonWithType:UIButtonTypeCustom];

  buttonImageNormal            = [UIImage imageNamed:@"social-button-bg.png"];
  stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];

  self.thirdButton.frame           = CGRectMake(10, (secondButton.frame.origin.y + secondButton.frame.size.height + 5), 300, 50);
  self.thirdButton.backgroundColor = [UIColor clearColor];

  [self.thirdButton setTitleColor:RGB(16,62,30) forState:UIControlStateNormal];
  [self.thirdButton setTitle:@"Share with Friends on" forState:UIControlStateNormal];
  [self.thirdButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
  [self.thirdButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

  CGRect thirdButtonFrame = thirdButton.titleLabel.frame;

  self.thirdButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
  self.thirdButton.titleEdgeInsets = UIEdgeInsetsMake(thirdButtonFrame.origin.x, thirdButtonFrame.origin.y + 20, 0, 0);

  [self addSubview:self.thirdButton];

  [super layoutSubviews];
}

- (void)dealloc {
  [firstButton release];
  [secondButton release];
  [thirdButton release];
  [super dealloc];
}

@end

// фрагмент кода вида

 self.uiasView = [[CustomUIASView alloc] initWithFrame:CGRectMake(0,    (self.view.frame.size.height + 270), kDefaultFrameWidth, 300)];

[self.uiasView.firstButton addTarget:self action:@selector(pushToRunwayViewController:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:self.uiasView];

"pushToRunwayViewController" равенникогда не звонил

0 голосов
/ 12 ноября 2010

Не уверен, что вы выяснили для себя, но когда вы добавляете target: self к своей firstButton, self - это ваш фактический пользовательский вид, а не контроллер представления.

Так что если вы переместите свой метод (pushToRunwayViewController) в CustomAISViewвсе должно работать как положено.

Надеюсь, это поможет.Рог

0 голосов
/ 20 октября 2010

Убедитесь, что вы делаете что-то вроде этого:

        UIButton *btn = [UIButton buttonWithType: UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 100, 40);
        [btn setTitle:@"Click Me" forState: UIControlStateNormal];
        [btn setBackgroundColor: [UIColor blackColor]];
        [btn setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonTap:) forControlEvents: UIControlEventTouchUpInside];
        [self.view addSubview:btn];

Это создаст кнопку, которая вызывает метод buttonTap при ее нажатии.

...