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

Ios 以编程方式设置UIButton上的图像和文本,ios,iphone,ios4,xcode4.2,Ios,Iphone,Ios4,Xcode4.2,我需要创建一个正常和突出显示的状态以及文本图像按钮编程。我无法使用Interface Builder构建它,因为我需要在UIScrollView上创建按钮。以下是我目前掌握的代码: - (void)loadView { CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame]; scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];

我需要创建一个正常和突出显示的状态以及文本图像按钮编程。我无法使用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
,则文本显示完美,否则不会。我可以同时拥有文本和图像吗?

ui按钮设置图像位于标题上方,因此您将无法看到标题下方的文本。 所以试着用setBackgroundImage设置按钮的图像

目标C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 
斯威夫特:

myButton.setBackgroundImage(buttonImage, forState: .normal)
你试过了吗

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted];

这可能会解决你的问题。

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

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 
而不是

[btn setImage:buttonImage forState:UIControlStateNormal]; 

这很好。

Swift 4

       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)

    }
  • 您可以将图像和文本一起设置为属性文本,您可以通过实现以下代码来实现这一点:
  • 这里我有一个自定义函数,您可以在其中传递标题字符串按钮图像,它将返回一个属性文本,您可以在ui按钮/ui标签上设置标题作为属性标题/文本
-如果要显示带有标题的图像前缀

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)
self.btnsuffix.setAttributedTitle(AttributedTextwithImageSuffix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " suffix avtar", buttonBound: self.btnsuffix), 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.btnprefix.setAttributedTitle(AttributedTextwithImagePrefix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " prefix avtar", buttonBound: self.prefix), for: .normal)
self.btnsuffix.setAttributedTitle(AttributedTextwithImageSuffix(AttributeImage: #imageLiteral(resourceName: "avtar"), AttributedText: " suffix avtar", buttonBound: self.btnsuffix), for: .normal)
输出将为


我认为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
}
}
以及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);
}
}
列举 延伸
  • 确保按钮的高度和宽度必须且应该大于图像


例如,如果要放置阿拉伯语文本,您能告诉我如何对齐文本(左对齐或右对齐)[yourButton.titleLabel setTextAlignment:UITextAlignmentLeft];如果我在iPad air 2上运行应用程序,我的图像仍然不适合按钮,因为它们的分辨率较低。任何关于如何拉伸它们以填充以及图像的建议都不会应用于背景。只是想指出,如果您想要稍微快一点的语法,uicontrol状态是不必要的。您能告诉我如何对齐文本吗,如果要放置阿拉伯语文本,请选择左侧或右侧。
myButton. setButtonWithTitleAndImage(fontSize : 15, fontType : "Poppins-Medium", textColor: UIColor.red, tintColor : UIColor.red, bgColor: UIColor.white, buttonImage: UIImage(named: "Bell.png"), imagePosition: .left, imageSizeHW: 30)