[英]Programmatically set image and text on 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];
}
但是按鈕上的文字沒有顯示。 如果我注釋掉button
的setImage
,則文本顯示完美,否則不會。 我可以同時擁有文本和圖像嗎?
UIButtons setImage 設置標題上方的圖像,因此您將無法看到其下方的文本。 因此,嘗試使用 setBackgroundImage 將圖像設置為您的按鈕。
目標-C:
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
迅速:
myButton.setBackgroundImage(buttonImage, forState: .normal)
你在那里犯了一個錯誤,你正在做
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
代替
[btn setImage:buttonImage forState:UIControlStateNormal];
這將正常工作。
斯威夫特 4
- 如果要顯示帶有標題的圖像前綴
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)
輸出將是
你有沒有嘗試過
[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
它可能會解決您的問題。
我認為 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);
}
}
enum buttonImageDirection: Int {
case left = 0
case right
case top
case bottom
}
extension UIButton{
func setButtonWithTitleAndImage(fontSize : CGFloat = 15, fontType : String = "Poppins-Medium", textColor: UIColor, tintColor : UIColor, bgColor:UIColor = .clear, buttonImage: UIImage?, imagePosition:buttonImageDirection = .left, imageSizeHW: CGFloat = 30){
if imageView != nil {
let image = buttonImage?.withRenderingMode(.alwaysTemplate)
self.setImage(image, for: .normal)
self.titleLabel?.font = UIFont(name: fontType, size: fontSize)
self.setTitleColor(textColor, for: .normal)
self.tintColor = tintColor
self.backgroundColor = bgColor
switch imagePosition{
case .left:
imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: (bounds.width - (imageSizeHW + 5)))
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: (imageView?.frame.width)!)
case .right:
imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - (imageSizeHW + 5)), bottom: 5, right: 5)
titleEdgeInsets = UIEdgeInsets(top: 0, left: (imageView?.frame.width)!, bottom: 0, right: 0)
case .top:
imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: (bounds.width - (imageSizeHW + 5)), right: 5)
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: (imageView?.frame.height)!, right: 0)
case .bottom:
imageEdgeInsets = UIEdgeInsets(top: (bounds.width - (imageSizeHW + 5)), left: 5, bottom: 5, right: 5)
titleEdgeInsets = UIEdgeInsets(top: (imageView?.frame.height)!, left: 0, bottom: 0, right: 0)
}
}
self.layoutIfNeeded()
}
}
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)
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.