ios 以编程方式在 UIButton 上设置图像和文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9887959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically set image and text on UIButton
提问by Haris Hussain
I need to create button programatically with an image for normal and highlighted state as well text. I cannot build it using Interface Builder, because I need to create buttons over a UIScrollView
. Here is the code I have so far:
我需要使用用于正常和突出显示状态以及文本的图像以编程方式创建按钮。我无法使用 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];
}
But the text on the button is not showing. If I comment out the setImage
for button
, then text shows perfectly, otherwise not. Can I have both text and an image at the same time?
但是按钮上的文字没有显示。如果我注释掉setImage
for button
,则文本显示完美,否则不会。我可以同时拥有文本和图像吗?
回答by iPrabu
UIButtons setImage sets the image above the title so you will not be able to see the text below it. So try to set image to your button with setBackgroundImage.
UIButtons setImage 设置标题上方的图像,因此您将无法看到其下方的文本。因此,请尝试使用 setBackgroundImage 将图像设置为您的按钮。
Objective-C:
目标-C:
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
Swift:
迅速:
myButton.setBackgroundImage(buttonImage, forState: .normal)
回答by Saroj Kumar ojha
You've made a mistake there, you're doing
你在那里犯了一个错误,你正在做
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
instead of
代替
[btn setImage:buttonImage forState:UIControlStateNormal];
This will work fine.
这将正常工作。
回答by Rana Anees
Have you tried
你有没有尝试过
[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
It might solve your problem.
它可能会解决您的问题。
回答by Marcin Szymański
I think Azharhussain Shaikh's answer is not working with larger images so I've twisted it a little and converted to a Swift 4 extension to UIButton. There you go:
我认为 Azharhussain Shaikh 的答案不适用于更大的图像,所以我稍微扭曲了它并转换为 UIButton的Swift 4 扩展。你去吧:
extension UIButton {
func setAttributedTextWithImagePrefix(image: UIImage, text: String, for state: UIControl.State) {
let fullString = NSMutableAttributedString()
if let imageString = getImageAttributedString(image: image) {
fullString.append(imageString)
}
fullString.append(NSAttributedString(string: " " + text))
self.setAttributedTitle(fullString, for: state)
}
func setAttributedTextWithImageSuffix(image: UIImage, text: String, for state: UIControl.State) {
let fullString = NSMutableAttributedString(string: text + " ")
if let imageString = getImageAttributedString(image: image) {
fullString.append(imageString)
}
self.setAttributedTitle(fullString, for: state)
}
fileprivate func getImageAttributedString(image: UIImage) -> NSAttributedString? {
let buttonHeight = self.frame.height
if let resizedImage = image.getResizedWithAspect(maxHeight: buttonHeight - 10) {
let imageAttachment = NSTextAttachment()
imageAttachment.bounds = CGRect(x: 0, y: ((self.titleLabel?.font.capHeight)! - resizedImage.size.height).rounded() / 2, width: resizedImage.size.width, height: resizedImage.size.height)
imageAttachment.image = resizedImage
let image1String = NSAttributedString(attachment: imageAttachment)
return image1String
}
return nil
}
}
and a extension to UIImage:
和 UIImage 的扩展:
extension UIImage {
func getResized(size: CGSize) -> UIImage? {
if UIScreen.main.responds(to: #selector(NSDecimalNumberBehaviors.scale)) {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale);
} else {
UIGraphicsBeginImageContext(size);
}
self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height));
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
func getResizedWithAspect(scaledToMaxWidth width: CGFloat? = nil, maxHeight height: CGFloat? = nil) -> UIImage? {
let oldWidth = self.size.width;
let oldHeight = self.size.height;
var scaleToWidth = oldWidth
if let width = width {
scaleToWidth = width
}
var scaleToHeight = oldHeight
if let height = height {
scaleToHeight = height
}
let scaleFactor = (oldWidth > oldHeight) ? scaleToWidth / oldWidth : scaleToHeight / oldHeight;
let newHeight = oldHeight * scaleFactor;
let newWidth = oldWidth * scaleFactor;
let newSize = CGSize(width: newWidth, height: newHeight);
return getResized(size: newSize);
}
}
回答by A.G
var menuButton:UIButton?
override func viewWillAppear(animated: Bool) {
menuButton = UIButton(frame: CGRectMake(0,0,30,30))
menuButton?.setBackgroundImage(UIImage(named: "menu.png"), forState: UIControlState.Normal)
}
回答by Azharhussain Shaikh
Swift 4
斯威夫特 4
- You can set the image and text together as a attribute text and you can do this by implementing below code:
- here i have customised function in which you can pass the title stringand button imageit will returned you an attributed text and you can set on UIButton/UILabel title as a attributed title/text.
- 您可以将图像和文本一起设置为属性文本,您可以通过实现以下代码来做到这一点:
- 在这里,我有自定义函数,您可以在其中传递标题字符串和按钮图像,它将返回一个属性文本,您可以将 UIButton/UILabel 标题设置为属性标题/文本。
- if you want to display an image prefix with title
- 如果要显示带有标题的图像前缀
func AttributedTextwithImagePrefix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString
{
let fullString = NSMutableAttributedString(string: " ")
let image1Attachment = NSTextAttachment()
image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - AttributeImage.size.height).rounded() / 2, width: AttributeImage.size.width, height: AttributeImage.size.height)
image1Attachment.image = AttributeImage
let image1String = NSAttributedString(attachment: image1Attachment)
fullString.append(image1String)
fullString.append(NSAttributedString(string: " " + AttributedText))
return fullString
}
this is how you can use this :
这是你如何使用它:
self.btnprefix.setAttributedTitle(AttributedTextwithImagePrefix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " prefix avtar", buttonBound: self.prefix), for: .normal)
- if you want to display an image suffix with title
- 如果要显示带有标题的图像后缀
func AttributedTextwithImageSuffix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString
{
let fullString = NSMutableAttributedString(string: AttributedText + " ")
let image1Attachment = NSTextAttachment()
image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - AttributeImage.size.height).rounded() / 2, width: AttributeImage.size.width, height: AttributeImage.size.height)
image1Attachment.image = AttributeImage
let image1String = NSAttributedString(attachment: image1Attachment)
fullString.append(image1String)
fullString.append(NSAttributedString(string: ""))
return fullString
}
this is how you can use this :
这是你如何使用它:
self.btnsuffix.setAttributedTitle(AttributedTextwithImageSuffix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " suffix avtar", buttonBound: self.btnsuffix), for: .normal)
OUTPUT WILL BE
输出将是