以编程方式在UIButton上设置图像和文本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了以编程方式在UIButton上设置图像和文本相关的知识,希望对你有一定的参考价值。

我需要以编程方式创建按钮,用于正常和突出显示的状态以及文本。我无法使用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];

}

但是按钮上的文字没有显示。如果我为setImage评论button,那么文字显示完美,否则不是。我可以同时同时拥有文字和图片吗?

答案

UIButtons setImage将图像设置在标题上方,这样您就无法看到它下面的文本。因此,尝试使用setBackgroundImage将图像设置为按钮。

Objective-C的:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

迅速:

myButton.setBackgroundImage(buttonImage, forState: .normal)
另一答案

你在那里犯了一个错误,你正在做

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

代替

[btn setImage:buttonImage forState:UIControlStateNormal]; 

这样可以正常工作。

另一答案

你有没有尝试过

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted];

它可能会解决您的问题。

另一答案

我认为Azharhussain Shaikh的答案不适用于较大的图像所以我将它扭曲了一点并转换为Swift 4扩展到UIButton。你去:

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
}
}

和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);
}
}
另一答案
       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)

    }
另一答案

斯威夫特4

  • 您可以将图像和文本一起设置为属性文本,您可以通过实现以下代码来实现:
  • 这里我有自定义功能,你可以传递标题字符串和按钮图像,它将返回一个属性文本,你可以在UIButton / UILabel标题上设置为属性标题/文本。

- 如果要显示带标题的图像前缀

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
}

这是你如何使用它:

self.btnprefix.setAttributedTitle(AttributedTextwithImagePrefix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " prefix avtar", buttonBound: self.prefix), for: .normal)

- 如果要显示带标题的图像后缀

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
}

这是你如何使用它:

self.btnsuffix.setAttributedTitle(AttributedTextwithImageSuffix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " suffix avtar", buttonBound: self.btnsuffix), for: .normal)

输出将是

enter image description here

以上是关于以编程方式在UIButton上设置图像和文本的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式设置 UIButton 文本颜色 [重复]

在 UIButton 上设置图像和标题

以编程方式更改UIButton的标题颜色,其标题设置为iOS 7中的属性

UIButton 标题标签文本未使用情节提要或以编程方式更改

设置 UIButton 图像并保持透明度

如何在 Swift 中以编程方式调整 UIButton 中文本的字体大小以适应宽度?