【问题标题】:iOS >> UIButton ImageView Property >> How to set Content Mode?iOS >> UIButton ImageView 属性 >> 如何设置内容模式?
【发布时间】:2014-01-21 05:03:11
【问题描述】:

有没有办法设置 UIButton Image、BackgroundImage 或 ImageView 属性 Content Mode 属性?

我试过直接的方法(当然没用……):

self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFit;

有一个带图片的按钮很好,但是如果没有办法正确设置它,它就不是很方便......

【问题讨论】:

  • "系统按钮的属性值为 nil。"来自 Apple 开发库。
  • 我过去解决此类问题的另一种方法是创建一个 UIImageView,在其中添加我的图片,然后在 UIImageView 之上添加一个自定义的空白 UIButton。当用户触摸图像时,他实际上是在触摸按钮。这样我就可以更好地控制图像及其属性。

标签: ios uiimageview uibutton contentmode


【解决方案1】:

如果你不想继承 UIButton,那么你可以试试这个,

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    for (UIView *view in button.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view setContentMode:UIViewContentModeScaleAspectFit];
        }
    }

【讨论】:

    【解决方案2】:

    使用带有自动布局的 iOS7/8,当 button 被布局时,button.imageView 不会被缩放,例如iPhone 6:

    (lldb) po button
    <UIButton: 0x7fb4f501d7d0; frame = (0 0; 375 275); opaque = NO; autoresize = RM+BM; tag = 102; layer = <CALayer: 0x7fb4f501d160>>
    
    (lldb) po button.imageView
    <UIImageView: 0x7fb4f51d21f0; frame = (0 0; 0 0); clipsToBounds = YES; hidden = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fb4f5152860>>
    

    设置button的图片后,button.imageView假设图片的大小,例如对于 320x240 图像:

    (lldb) po button.imageView
    <UIImageView: 0x7fb4f51d21f0; frame = (27.5 17.5; 320 240); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fb4f5152860>>
    

    看起来button.imageView 不尊重其内容模式,但实际上,问题在于button.imageView 的大小。

    答案也是设置button的内容对齐方式。

    以下设置button的图片,设置button.imageView的内容模式,并使button.imageView适合button的大小:

    [button setImage:image forState:UIControlStateNormal];
    button.imageView.contentMode = UIViewContentModeScaleAspectFill;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    

    现在,button.imageView 的大小与button 相同,并且具有所需的内容模式。

    (lldb) po button.imageView
    <UIImageView: 0x7faac219a5c0; frame = (0 0; 375 275); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7faac219a6c0>>
    

    从而达到预期的结果。很方便!

    【讨论】:

    • 为 UIControlStateHighlighted 设置单独的图像时,这似乎不起作用
    • 在图像视图上将内容模式设置为“缩放以填充”,在按钮上将 h & v 对齐设置为“填充”。也适用于 xamarin。
    【解决方案3】:

    每个 UIButton 都有一个隐藏的 UIImageView。所以我们必须像下面给出的方式设置内容模式......

    [[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
    

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多