自定义 UIView 不显示

Custom UIView doesnt show

我有一个非常简单的 UIView 来创建框,但是发生的是 UIView 根本不显示,这是我在 sharingButtons.m

上的代码
-(void)createContainer{

winWidth = [UIScreen mainScreen].bounds.size.width;


buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, winWidth, 20)];
buttonContainer.backgroundColor = [UIColor redColor];


[self.view addSubview:buttonContainer];

 }


-(void)createButton{
[self createContainer];
}

这是我的 sharingButtons.h

 @interface SocialSharing : UIViewController {
int winWidth;
 }

- (void)createButton;
- (void)createContainer;

#pragma mark - Properties

@property(nonatomic, strong) UIView* buttonContainer;

@end

并且 createButton 方法在 viewDidLoad

MyViewControler.m 调用

我的代码有问题吗??

已编辑

这是我在 MyViewControler.m

上的代码
- (void)loadSocialSharingButton {

socialButtons = [[SocialSharing alloc] init];

[socialButtons createButton];
}

- (void)viewDidLoad {

[super viewDidLoad];

[self loadSocialSharingButton];

}

抱歉,我刚刚了解 obj c :)

非常感谢

您的 SocialSharingUIViewController 的子类。

然后将 buttonContainer view 添加到此 SocialSharing Controller,如果您只是调用

,则此控制器不在屏幕上
socialButtons = [[SocialSharing alloc] init];

[socialButtons createButton];

所以,你什么也看不到。

您当前是@MyViewController,但是您正在加载您的自定义视图@SocialSharing ViewController,两者 ViewController 是不同的,您不能只在通过初始化将社交分享到 MyViewController。

您已将 SocialSharing class 更改为 UIView 的子 class 并初始化此视图并添加到 MyViewController.

的子视图

SocialSharing.h

@interface SocialSharing : UIView {
int winWidth;
}
- (instancetype)createButton;
#pragma mark - Properties
@property(nonatomic, strong) UIView* buttonContainer;
@end

SocialSharing.m

- (instancetype)createButton
{
   winWidth = [UIScreen mainScreen].bounds.size.width;
   self = [super initWithFrame:CGRectMake(0, 0, winWidth, 20)];
   if (self) {
     buttonContainer = [[UIView alloc] initWithFrame:];
     buttonContainer.backgroundColor = [UIColor redColor];
     [self addSubview:buttonContainer];
   }
   return self;
}

MyViewController.m

- (void)viewDidLoad {
  [super viewDidLoad];
  [self loadSocialSharingButton];
  }
- (void)loadSocialSharingButton {
  socialButtons = [SocialSharing alloc] createButton];
  [self.view addSubView:socialButtons];
  }

您的 buttonContainer 不可见的原因是它没有加载到您的视图层次结构中。

要使其可见,您应该将其添加为子视图。 In MyViewController.m in viewDidLoad[self loadSocialSharingButton];

后添加以下行
[self.view addSubview:socialButtons.buttonContainer];

希望对您有所帮助!

在一个 iOS 应用程序中,一次只有一个 ViewController 处于活动状态。因为你在 MyViewController,所以 MyViewController 是活动的,如果你想导航到任何其他视图控制器而不是你需要呈现或推送相同的实例。这样做将使另一个视图控制器处于活动状态。

在你的情况下,问题是你的 SocialSharingUIViewController 的子类,因为它被创建为 SocialSharing : UIViewController 并且它不是活动的,所以在它上面添加任何视图都不会可见,因为 SocialSharing 的实例不是 pushed/ presented。如果您需要显示来自 SocialSharing 的视图,那么您可以从 UIView 对其进行子类化,或者推送/呈现 SocialSharing 的实例以使其视图处于活动状态和可见状态。