36

我创建了一个按钮网格。以下代码创建按钮并显示它们,但按钮上没有文本。有没有我缺少的设置?(Obj-C 回复很好,我会双语)

RectangleF frame = new RectangleF (X + 3, Y + 3, cellWidth - 2, cellHeight - 2);
UIButton button = new UIButton (frame);
button.TitleLabel.Text = "Baha'i";
button.TitleLabel.Font = UIFont.FromName ("Helvetica-Bold", 15);
button.TitleLabel.TextColor = UIColor.Black;
button.TitleLabel.Frame = frame;
button.BackgroundColor = UIColor.FromWhiteAlpha(.5f,.5f);
this.AddSubview (button);
4

7 回答 7

132

我想你想要setTitle: forState:

[button setTitle:@"Baha'i" forState:UIControlStateNormal]
于 2010-03-07T02:41:27.047 回答
6

UIButton 继承自 UIView,因此添加文本和图像的另一种方法是添加子视图。例子:

// My Image
UIImage *buttonImage = [UIImage imageNamed:@"myImage.png"];
UIImageView *buttonImageView = [[[UIImageView alloc] 
    initWithFrame:CGRectMake(0, 0, 
    buttonImage.size.width,buttonImage.size.height)] autorelease];
[buttonImageView setImage:buttonImage];

// My Label
UILabel* titleLabel = [[[UILabel alloc] 
    initWithFrame:CGRectMake(0, 0, 
    buttonImage.size.width, buttonImage.size.height)] autorelease];
titleLabel.text = @"My Text";
titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size: 11.0];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = UITextAlignmentCenter;

// Create Button with Image and Label
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addSubview:buttonImageView];
[button addSubview:titleLabel];
于 2011-05-05T19:14:26.807 回答
3
UIButton *  selectCountryBtn =  [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];  

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

在这里,我以编程方式创建示例按钮,然后为其正常控件状态设置标题,您可以使用自己的按钮对象来设置标题字符串,此外,您还可以通过将 UIControlStateNormal 更改为另一个所需的来设置另一个控件状态的标题文本状态。

于 2012-03-02T07:30:31.767 回答
2

对于 swift 开发人员-

button.setTitle("Your button Name", for: .normal)
于 2016-10-08T11:59:16.857 回答
2

就我而言(Swift 4),它是以下内容:

btnLogin.setTitle("Welcome, " + var_name, for: [])
于 2018-11-15T00:07:58.263 回答
0
self.ButtonName.setTitle("Here Put Your variable model", for: .normal)
于 2021-02-28T13:57:30.010 回答
-4
  self.Button_name.titleLabel.text = @"Your title name";
于 2013-02-26T10:57:58.680 回答