UIButton 的 title 属性正确记录但在将按钮添加为子视图时未显示

Posted

技术标签:

【中文标题】UIButton 的 title 属性正确记录但在将按钮添加为子视图时未显示【英文标题】:UIButton's title property logs correctly but not showing up when adding button as subview 【发布时间】:2014-10-07 05:37:37 【问题描述】:

我创建了一个 UIButton,我可以成功地将它添加为子视图并在屏幕上看到它。问题是,当我尝试使用时:

[myButton setTitle:@"My Title" forState:UIControlStateNormal];

当我运行应用程序时,该按钮不显示标题。如果我在使用上述方法后 NSLog 按钮的标题,它实际上已被设置为我传入的标题。

这是我的代码。这是在 UIView 子类中。我意识到其中一些逻辑可能不属于 UIView 子类,但我只是想让它尽快工作:

// Set the view's frame, background color, corner radius
self.frame = CGRectMake(45, 200, 235, 187);
self.backgroundColor = [UIColor whiteColor];
self.layer.borderWidth = 1;
self.layer.borderColor = [UIColor grayColor].CGColor;
self.layer.cornerRadius = 5;

// Create the popup's body text label
self.popupBodyTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 150)];
self.popupBodyTextLabel.text = @"Text goes here.";

// Add text view to popup's subviews
[self addSubview:self.popupBodyTextLabel];

// Create ok button
UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 143, 120, 44)];
myButton.backgroundColor = [UIColor whiteColor];
myButton.layer.borderWidth = 1;
myButton.layer.borderColor = [UIColor grayColor].CGColor;
[myButton setTitle:@"OK" forState:UIControlStateNormal];


// Round the button's bottom left corner
UIBezierPath *myButtonMaskPath = [UIBezierPath bezierPathWithRoundedRect:myButton.bounds byRoundingCorners:(UIRectCornerBottomLeft) cornerRadii:CGSizeMake(5.0, 5.0)];

CAShapeLayer *okButtonMaskLayer = [[CAShapeLayer alloc] init];
myButtonMaskLayer.frame = myButton.bounds;
myButtonMaskLayer.path = myButtonMaskPath.CGPath;
myButton.layer.mask = myButtonMaskLayer;


// Add selector to button
[myButton addTarget:self action:@selector(myButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

// Add button to subviews
[self addSubview:myButton];

// Create the background view
self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
self.backgroundView.backgroundColor = [UIColor grayColor];
self.backgroundView.alpha = 0.5f;

// Show our new views
[[[UIApplication sharedApplication] keyWindow] addSubview:self.backgroundView];
[[[UIApplication sharedApplication] keyWindow] addSubview:[MPPopupView shared]];

【问题讨论】:

为按钮添加任意字体颜色 【参考方案1】:

设置按钮标题的代码是对的,所以用这段代码设置标题颜色

   [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

【讨论】:

以上是关于UIButton 的 title 属性正确记录但在将按钮添加为子视图时未显示的主要内容,如果未能解决你的问题,请参考以下文章

在 Interface Builder 中设置为 UIButton 的 Attributed Title 属性在应用程序中被忽略

UIButton 显示 BackgroundImage、Image 和 Title

UIButton Title 只显示一半

UIButton 图像在 IB 中看起来不错,但在应用程序上显示时会被拉伸

UIButton 在所有设备上的形状都不正确

如何向 UIButton 添加阴影?