2016-11-18 102 views
0

我有一個圖像和UIButton的標題。那我試圖讓我的圖像(寬度15像素),以左對齊和我的標題對齊5px的左:titleEdgeInsets for UIButton沒有意義

Button Example

按鈕的寬度爲215,但我不得不把我的titleEdgeInset到-44。這沒有意義。什麼是數學得到-44?

回答

3

這是因爲一個按鈕的圖像和標題默認集中在一起。

例如,這裏有一個300像素寬按鈕,圖像和文字,沒有插圖:

Default button spacing

看起來我需要的按鈕,內容左移60點離開,所以-60左插圖和60右插入。

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0) 
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0) 

enter image description here

編輯:

這些插圖也將在上面的例子中工作。

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0) 
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0) 

該按鈕爲中心的內容,所以如果你說「還有2個點左側的」按鈕,將在由1角移動它的內容,讓他們爲中心。

規則是

-leftInset + rightInset = LEFTMARGIN * 2

+0

似乎擁有正確的邊緣插入將視圖帶出框架。這是我做錯了什麼嗎? –

+0

而且,如果我想調整圖像大小,我可以使用這種方法嗎? –

+0

如果-44正在爲你工作,那麼你也可以做(0.0,-22.0,0.0,22.0)。編輯上面解釋。調整大小取決於你想要做什麼。如果你設置頂部的插圖,圖像將被垂直砸碎,然後你可以設置內容模式,使其縮放以適應...更多信息請點擊這裏http://stackoverflow.com/questions/10576593/how-to-adjust-an -uibuttons-IMAGESIZE – charmingToad

0

它很容易做到:

在swift3:

let button: UIButton = UIButton.init(frame: CGRect.init(x: 44, y: 64, width: 100, height: 40)) 

    button.backgroundColor = UIColor.clear 
    button.setImage(UIImage.init(named: "img"), for: UIControlState.normal) 
    button.setTitle("hello", for: UIControlState.normal) 
    button.layer.borderWidth = 1 
    button.layer.borderColor = UIColor.blue.cgColor 
    button.layer.cornerRadius = 4 

    // set edge inset 
    button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -40, bottom: 0, right: 0) 
    button.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -20, bottom: 0, right: 0) 

    self.view.addSubview(button) 

在Objective-C:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(44, 64, 100, 40); 
    button.backgroundColor = [UIColor clearColor]; 
    [button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal]; 
    [button setTitle:@"hello" forState:UIControlStateNormal]; 
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

    button.layer.cornerRadius = 4; 
    button.layer.borderColor = [UIColor blueColor].CGColor; 
    button.layer.borderWidth = 1; 
    // set edge inset 
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0); 
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0); 
    [self.view addSubview:button]; 

The result

+0

我理解它是怎麼做的,我只是不明白的地方的數字-40和-30從何而來。它們與框架寬度有什麼關係? –