ios代碼調整button圖片image文字title位置

來源:互聯網
上載者:User

標籤:ios 按鈕圖片文字位置調整   button調整image位置   

自訂一個button,要調整 button中的image(注意,不是backgroundImage) 和  title 文字的位置,只需要重寫  Button類獨對應的兩個方法即可:

首先,我們來建立一個 SuperButton繼承自 UIButton

////  SuperButton.h//  SuperButton////  Created by 楊斌 on 14/12/25.//  Copyright (c) 2014年 楊斌. All rights reserved.//#import <UIKit/UIKit.h>@interface SuperButton : UIButton@end

實現檔案

////  SuperButton.m//  SuperButton////  Created by 楊斌 on 14/12/25.//  Copyright (c) 2014年 楊斌. All rights reserved.//#import "SuperButton.h"#import "UtilsFunctions.h"@interface SuperButton (){    CGRect boundingRect;       }@end@implementation SuperButton//自訂的初始化方法- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self)    {                [self setTitle:@"項目介紹" forState:UIControlStateNormal];        [self.titleLabel setFont:[UIFont boldSystemFontOfSize:font]];        [self setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal];        [self setImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal];        boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,font) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];    }    return self;}
1.重寫方法,改變 圖片的位置  在  titleRect..方法後執行- (CGRect)imageRectForContentRect:(CGRect)contentRect{    CGFloat imageX=self.frame.size.width/2+boundingRect.size.width/2;    UIScreen *s=[UIScreen mainScreen];    CGRect rect=s.bounds;    CGFloat imageY=contentRect.origin.y+14;    CGFloat width=24;    CGFloat height=24;    return CGRectMake(imageX, imageY, width, height);    }2.改變title文字的位置,構造title的矩形即可- (CGRect)titleRectForContentRect:(CGRect)contentRect{        CGFloat imageX=(self.frame.size.width-boundingRect.size.width)/2;    CGFloat imageY=contentRect.origin.y+10;    CGFloat width=220;    CGFloat height=25;    return CGRectMake(imageX, imageY, width, height);}@end
我們只要重寫 上述的兩個方法,就可以實現對  button按鈕中的圖片和文字的位置的調整
注意: 1.ios7和ios8系統上 上述兩個方法 啟動並執行次數會有差異,可以設定標誌位,或者自訂一個 button(不要整合button)
      2.代碼是經過刪減的,大家關鍵是重寫上面的兩個方法,重新繪製矩形,即可


ios代碼調整button圖片image文字title位置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.