【发布时间】:2021-12-29 01:33:27
【问题描述】:
我已经在自定义 UIView CustomButtonView 中放置了一个 UIButton。 UIButton 没有响应点击/单击事件,并且没有触发其相应的选择器方法。下面是我的代码;我做错了什么?
同样,自定义视图的背景颜色为红色。当我将自定义视图添加到视图控制器的视图中时,会显示红色矩形。但是,当我将 UIButton 添加到自定义视图(背景颜色为红色)时,仅显示 UIButton,而不显示红色矩形。为什么会这样?
//
// CustomButtonView.h
//
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface CustomButtonView : UIView
@property (strong, nonatomic) UIImageView *buttonImageView;
@property (strong, nonatomic) UIButton *button;
@end
NS_ASSUME_NONNULL_END
//
// CustomButtonView.m
//
#import "CustomButtonView.h"
@implementation CustomButtonView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor redColor];
_button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.backgroundColor = [UIColor greenColor];
[_button setTitle:@"john doe" forState:UIControlStateNormal];
[_button setTitle:@"john doe" forState:UIControlStateHighlighted];
_button.translatesAutoresizingMaskIntoConstraints = NO;
_button.titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
_button.titleLabel.textColor = [UIColor whiteColor];
self.userInteractionEnabled = NO;
self.button.userInteractionEnabled = YES;
//[self addSubview:_button];
//[_button.topAnchor constraintEqualToAnchor:self.topAnchor].active = YES;
//[_button.leadingAnchor constraintEqualToAnchor:self.leadingAnchor].active = YES;
}
return self;
}
@end
//
// ViewController.m
// TestApp
//
//
#import "ViewController.h"
#import "CustomButtonView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor yellowColor];
_customButtonView = [[CustomButtonView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
_customButtonView.backgroundColor = [UIColor redColor];
_customButtonView.translatesAutoresizingMaskIntoConstraints = NO;
[_customButtonView.button addTarget:self action:@selector(customButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_customButtonView];
}
- (void)customButtonTapped:(id)sender{
NSLog(@"Button tapped!");
}
@end
下面是一些屏幕截图。请点击链接。
【问题讨论】:
标签: ios objective-c uiview uibutton