2013-06-25 19 views
4

如果我這樣做,那麼titleView將得到拉伸:如何設置UIImageView作爲一個標題,使東西不拉伸?

UIImage * img =[UIImage imageNamed:@"isikota_small.png"]; 
UIImageView * uiImage= [[UIImageView alloc]initWithImage:img]; 
self.navigationItem.titleView = uiImage; 

PO(self.navigationItem.titleView); 

如果我做

UIImage * img =[UIImage imageNamed:@"isikota_small.png"]; 
UIImageView * uiImage= [[UIImageView alloc]initWithImage:img]; 
uiImage.frame = CGRectMake(0,0,66,33); 

uiImage.autoresizingMask = UIViewAutoresizingFlexibleHeight; 
//[self.navigationItem.titleView addAndResizeSubView:uiImage]; doesn't work 


self.navigationItem.titleView = uiImage; 
PO(self.navigationItem.titleView); 

標題視圖也將得到延伸。

如果我做的:

UIImage * img =[UIImage imageNamed:@"isikota_small.png"]; 
UIImageView * uiImage= [[UIImageView alloc]initWithImage:img]; 
uiImage.frame = CGRectMake(0,0,66,33); 

uiImage.autoresizingMask = UIViewAutoresizingFlexibleHeight; 
//[self.navigationItem.titleView addAndResizeSubView:uiImage]; doesn't work 
UIView * uiv = [[UIView alloc]init]; 
[uiv addSubview:uiImage]; 
uiv.frame = CGRectMake(127, 0, 66, 33); 
uiv.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth; 

self.navigationItem.titleView = uiv; 
PO(self.navigationItem.titleView); 

不知怎的,蘋果改變了uiv.frameCGRectMake(127, 6, 66, 33)

必須有一個優雅的解決方案。

+0

什麼是您的圖像高度和寬度? – sagarcool89

+0

可能是'stretchableImageWithLeftCapWidth'可以救你。 – rptwsthi

+0

66 * 33這是圖像的寬度和高度。 –

回答

4

當您使用自定義視圖爲titleView,以及在tableViews和其他類似用例中的分節頁腳和標題時,iOS將忽略視圖框架的偏移部分或以某種難以預測的方式更改它。爲了去解決這個問題,你需要創建一個容器視圖,以便您的容器具有偏移(0,0):

嘗試是這樣的:

UIImage * img =[UIImage imageNamed:@"isikota_small.png"]; 
UIImageView * uiImage= [[UIImageView alloc]initWithImage:img]; 
uiImage.frame = CGRectMake(127,0,66,33); 

UIView * uiv = [[UIView alloc]init]; 
[uiv addSubview:uiImage]; 
uiv.frame = CGRectMake(0, 0, 66+127, 33); 

self.navigationItem.titleView = uiv; 

我不知道,如果自動尺寸口罩也會拋棄它,所以嘗試沒有任何掩碼,看看你是否能得到你想要的行爲。

+0

我爲此添加了一個UIView。事情就是搞砸了。你自己試過這個嗎? –

+0

是的,我正在使用類似這樣的東西。我不確定你的意圖是在titleView中調整圖像的大小,因爲我只用它來調整標題的位置,而不是它的大小。如果您仍然遇到問題,請嘗試爲您的問題添加屏幕截圖,以便我們看到問題所在以及您希望的樣子。 – SaltyNuts

+0

真棒回答:) –

相關問題