2017-06-16 164 views
-1

我有一個問題,當我嘗試創建一個UIButton有以下選項:標題對齊左,右圖像對齊,UIButton的標題爲對齊左右圖像靠右側

我想這樣做編程,這裏是我tryed,到目前爲止,它的工作原理,但並不像我想

UIButton *definition_title = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
       definition_title.frame = CGRectMake(0,0, accordion.frame.size.width, 70.0f); 
       [definition_title setImage:[UIImage imageNamed:@"image_name.png"] forState:UIControlStateNormal]; 
       definition_title.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10); 
       definition_title.imageView.contentMode = UIViewContentModeScaleAspectFit; 
       [definition_title setTitle:@"Scan the Barcode" forState:UIControlStateNormal]; 
       definition_title.titleEdgeInsets = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f); 
       definition_title.imageEdgeInsets = UIEdgeInsetsMake(0.0f, accordion.frame.size.width-50, 0.0f, 0.0f); 
       definition_title.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 

上面返回代碼,我的UIButton喜歡這個

________________ 
    | text image| 

,但我想它喜歡

________________ 
    |text  image| 
+0

我認爲那是因爲你的標題標籤居中對齊,加入這行definition_title.titleLabel.textAlignment = NSTextAlignmentLeft; – Hima

回答

0

方法1:

添加標題和按鈕圖像,並調整標題和圖像的插圖,使文本和圖像顯示在按鈕

enter image description here

兩側

方法2:

創建UIButton的子類並覆蓋func imageRect(forContentRect contentRect: CGRect) -> CGRectfunc titleRect(forContentRect contentRect: CGRect) -> CGRect,併爲標題和圖像提供CGRect。

例子:

import UIKit 

class MyTestButton: UIButton { 

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect { 
     return CGRect(x: self.frame.maxX - contentRect.height/*specify your button width here am using height */, y: 0, width: contentRect.height/*specify your button width here am using height */, height: contentRect.height) 
    } 

    override func titleRect(forContentRect contentRect: CGRect) -> CGRect { 
     return CGRect(x:0, y:0, width: self.bounds.size.width - self.imageRect(forContentRect:contentRect).width,height: contentRect.height) 
    } 
} 

O/P:

enter image description here

+0

我需要這個 –

+0

的確切oposite版本@ bonta-alexandru:共同的朋友:)你可以滑動框架:) –

+0

這是偉大的,但我不想子類UIButton,我需要在Obj-C中寫,我也需要以編程方式執行 –