Using stretchable images in Xcode storyboards

前端 未结 5 1087
慢半拍i
慢半拍i 2020-12-22 21:02

I\'m using storyboards to layout my view controllers and I would like to use stretchable images for my buttons (so that I don\'t need to generate several images with differe

5条回答
  •  余生分开走
    2020-12-22 22:01

    Here's what I did: I set an outlet for the button and connected it, then did this in viewDidLoad:

    [self.someButton setBackgroundImage:[[self.someButton backgroundImageForState:UIControlStateNormal] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 4, 3)] forState:UIControlStateNormal];
    

    This makes it so it reuses the image you set in the storyboard, so if you change it from one color to another it will work, as long as the insets dont change.

    For a view that had many of these things, I did this:

    for (UIView * subview in self.view.subviews) {
            if ([subview isKindOfClass:[UIImageView class]] && subview.tag == 10) {
                UIImageView* textFieldImageBackground = (UIImageView*)subview;
                textFieldImageBackground.image = [textFieldImageBackground.image stretchableImageWithLeftCapWidth:7 topCapHeight:5];
            } else if([subview isKindOfClass:[UIButton  class]] && subview.tag == 11) {
                UIButton * button = (UIButton*)subview;
                [button setBackgroundImage:[[button backgroundImageForState:UIControlStateNormal] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 4, 3)] forState:UIControlStateNormal];
            }
        }
    

    Note that I set the tags for all the ones I wanted stretched.

    I'm in the same boat as you though, I'd love being able to set these very UI centric things on the storyboard itself.

提交回复
热议问题