我需要以编程方式创建按钮,其中包含用于正常和突出显示状态以及文本的图像。我无法使用 Interface Builder 构建它,因为我需要在 UIScrollView
上创建按钮。这是我到目前为止的代码:
- (void)loadView {
CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame];
scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];
scrollView.contentSize=CGSizeMake(320,960);
UIImageView *tempImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.jpeg"]];
UIImage * buttonImage = [UIImage imageNamed:@"contentlist_active.png"];
self.view=scrollView;
[scrollView addSubview:tempImageView2];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(22, 100, 277, 32);
[btn setImage:buttonImage forState:UIControlStateNormal];
[btn setTitle:@"hello world" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[scrollView addSubview:btn];
}
但是按钮上的文字没有显示。如果我为 button
注释掉 setImage
,那么文本会完美显示,否则不会。我可以同时拥有文字和图片吗?
最佳答案
UIButtons setImage 将图像设置在标题上方,因此您将无法看到其下方的文本。 因此,请尝试使用 setBackgroundImage 将图像设置为您的按钮。
objective-C :
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
swift :
myButton.setBackgroundImage(buttonImage, forState: .normal)
关于ios - 以编程方式在 UIButton 上设置图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887959/