設置UIButton的文字和圖片顯示位置、字體的大小、字體的顏色

btn.frame = CGRectMake(x, y, width, height);

[btn setTitle: @"search" forState: UIControlStateNormal];

//設置按鈕上的自體的大小

//[btn setFont: [UIFont systemFontSize: 14.0]];??? //這種可以用來設置字體的大小,但是可能會在將來的SDK版本中去除改方法

//應該使用

btn.titleLabel.font = [UIFont systemFontOfSize: 14.0];

[btn seBackgroundColor: [UIColor blueColor]];

//最后將按鈕加入到指定視圖superView

[superView addSubview: btn];

==========================================================

tvnamelabel=[[UIButton alloc]initWithFrame:CGRectMake(5,5,200,40)];

這樣初始化的button,文字默認顏色是白色的,所有如果背景也是白色的話,是看不到文字的,

btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//設置文字位置,現設為居左,默認的是居中

[btn setTitle:@“title”forState:UIControlStateNormal];// 添加文字

有些時候我們想讓UIButton的title居左對齊,我們設置

btn.textLabel.textAlignment = UITextAlignmentLeft

是沒有作用的,我們需要設置

btn.contentHorizontalAlignment = UIControlContentHorizonAlignmentLeft;

但是問題又出來,此時文字會緊貼到做邊框,我們可以設置

btn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);

使文字距離做邊框保持10個像素的距離。

=======================================================

設置UIButton上字體的顏色設置UIButton上字體的顏色,不是用:

[btn.titleLabel setTextColor:[UIColorblackColor]];

btn.titleLabel.textColor=[UIColor redColor];

而是用:

[btn setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];

增加一個 UIButton 上設置不同顏色的字體,也可設置其大小等

NSString* aStr =@"本人是個大帥哥";

NSMutableAttributedString*str = [[NSMutableAttributedStringalloc] initWithString:[NSStringstringWithFormat:@"%@",aStr]];?

[str addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"Arial-BoldItalicMT"size:16.0] ?range:NSMakeRange(0,3)];

[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColorgreenColor]range:NSMakeRange(0,3)];

UIButton* butn = [UIButtonbuttonWithType:UIButtonTypeCustom];? ?

butn.backgroundColor = [UIColororangeColor];

butn.frame =CGRectMake(100,200,200,30);?

[butn setAttributedTitle:str forState:UIControlStateNormal];? ?

[butn addTarget:selfaction:@selector(click) forControlEvents:UIControlEventTouchUpInside];? ?

[self.view addSubview:butn];

設置 button 顯示網絡圖片自適應的方法為:

[buttonsd_setImageWithURL:[NSURLURLWithString:pictureModel.url]forState:UIControlStateNormalplaceholderImage:[UIImageimageNamed:@"Placeholder_240x240.png"]];

[button.imageViewsetContentMode:UIViewContentModeScaleAspectFill];

感覺雖然這都是一些簡單東西,但有時候有一些小細節注意不到,記錄下來希望能幫到有需要的人.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容