Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set UIImageView as a title so that the stuff is not stretch?

If I do the following, then titleView will get stretched:

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

PO(self.navigationItem.titleView);

If I do

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);

the title view will also get stretched.

If I do:

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);

Somehow Apple changes the uiv.frame to CGRectMake(127, 6, 66, 33).

There has to be an elegant solution.

like image 599
Septiadi Agus Avatar asked Dec 05 '25 15:12

Septiadi Agus


1 Answers

When you use custom views as titleView, as well as for section footers and headers in tableViews and other similar use cases, iOS will ignore the offset part of your view's frame or change it in some not readily predictable way. To go around this issue you will need to create a container view such that your container has offsets (0,0):

Try something like this:

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;

I'm not sure if the autoresizing masks are throwing it off as well, so try it without any masks and see if you can get the behaviour you want.

like image 114
SaltyNuts Avatar answered Dec 08 '25 08:12

SaltyNuts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!