How to set UIImageView as a title so that the material does not stretch?

If I do the following, the titleView will stretch:

 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 will also be stretched.

If I do this:

 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 is changing uiv.frame to CGRectMake(127, 6, 66, 33) .

There must be an elegant solution.

+4
source share
1 answer

When you use custom views as a titleView , as well as for footers and section headers in table views and other similar use cases, iOS will ignore the shifted part of your view or change it in some way that is not predictable. To get around this problem, you need to create a container view so 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 that autoresist masks also drop it, so try it without any masks and see if you can get the behavior you need.

+4
source

Source: https://habr.com/ru/post/1488084/


All Articles