2015-09-30 41 views
0

我正在通過一個nib文件構建一個UITableViewCell。我也有一個相應的UITableViewCell子類的筆尖的插座連接到。動態更改圖像視圖寬度以匹配標籤文本寬度的最佳方法?

我需要一個動態大小的UIImageView(只有寬度)作爲我的tableviewcell標籤的背景。有沒有一種方法可以通過自動佈局來實現?

我已經嘗試設置的ImageView作爲標籤的代碼中的一個子視圖:

[theLabel sizeToFit] 
CGRect boundingRect = [theLabel.text boundingRectWithSize: theLabel.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:0 context:0]; 
UIImageView *background = [[UIImageView alloc]initWithFrame:boundingRect]; 
background.image = [UIImage imageNamed: @"validImageName"]]; 
[theLabel addSubview: background]; 

然而,這不會導致正確的框架。我也考慮過使用[UIColor colorWithPatternImage: @"aValidImageName"];設置標籤的背景,但是這不包括背景圖像上的填充。此外,背景圖像包含我想保留的圓角(這種方法會削減)。任何想法都表示讚賞。

+0

您是否嘗試添加UIImageView作爲UILabel自動佈局的子視圖? –

+0

我沒有意識到這是一個選項,我會怎麼做呢? @Rage – BenJammin

回答

0

嘗試此,

1)可以使用自動調整大小根據屏幕的大小來改變圖像的寬度。

(OR)

2)設置自定義框架爲您的ImageView

例:

UIImageView *background = [[UIImageView alloc]initWithFrame:(0,0,Your_Custom_Width_Size_Value,100)]; 
background.image = [UIImage imageNamed: @"validImageName"]]; 
[theLabel addSubview: background]; 

         (or) 

//改變根據標籤

UIImageView *background = [[UIImageView alloc]initWithFrame:(0,0,Your_Label_Name.frame.size.width,100)]; 
    background.image = [UIImage imageNamed: @"validImageName"]]; 
    [theLabel addSubview: background]; 
+0

我不知道autoresizing,我看着它,改變了我的方法。謝謝! – BenJammin

+0

@Benjammin,歡迎各方。感謝回覆...... :) –

0

我寬會建議你使用UIView對象作爲容器和將你的UIImageView和UILabel作爲子視圖添加到它。將約束添加到Image View和Label中,使其高度和寬度總是與Superview相等。然後只要給容器UIView任何你想要的框架。