【问题标题】:UIButton IB vs programmaticallyUIButton IB 与编程方式
【发布时间】:2012-03-19 01:24:52
【问题描述】:

当我在界面生成器中制作一个带有背景的自定义 UIButton 时,它为我提供了这个默认功能,即当我在内部进行触摸时,它会使图像变黑。 如果我以编程方式创建 UIButton,如下所示:

    buttonPic = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 100, 63)];
    [[buttonPic imageView] setContentMode:UIViewContentModeScaleToFill];

[buttonPic setImage:[video pic] forState:UIControlStateNormal];

它根本不像我在 IB 中创建的那样。当我在里面修饰时,什么都没有改变。 UIButton 中是否有我缺少的设置? 谢谢

【问题讨论】:

    标签: objective-c ios cocoa-touch uibutton


    【解决方案1】:

    这是以编程方式创建 UIButton 的方法。

    //Specify the type of the button first. No need to use alloc-init for UIButton like other view objects.
    
    UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    
    // Give UIButtonTypeRoundedRect to get default Interface builder style button. 
    
    myBtn.frame = CGRectMake(0, 0, 100, 40);
    [self.view addSubview:myBtn];
    
     // Since the button type is custom, give an image to make it visible.
    [myBtn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:normal];
    [myBtn addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // These are some optional methods you may want to use.
    
    myBtn.titleLabel.font = [UIFont fontWithName:@"Arial" size:15];
    [myBtn setTitle:@"my button" forState:UIControlStateNormal];
    [myBtn setTitleColor:[UIColor blackColor] forState:normal];
    [myBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    

    【讨论】:

      【解决方案2】:

      我认为您必须启用以下两个选项之一:

      buttonPic.showsTouchWhenHighlighted = YES;
      buttonPic.reversesTitleShadowWhenHighlighted = YES;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        • 2015-02-27
        • 1970-01-01
        • 2012-09-21
        • 2013-02-09
        • 2013-08-31
        • 1970-01-01
        相关资源
        最近更新 更多