按钮UIBUtton的常用属性及方法总结

来源:互联网 发布:方齐禾淘宝 编辑:程序博客网 时间:2024/06/15 01:11

button中的图片文字排列:默认时图片在左,文字在右   

注意:设置按钮文字的状态不能用UIControlStateHighLighted否则控制台会报警告   可以用选中状态的UIControlStateSelected


 // 实例化一个button

    UIButton *headerButton = [[UIButtonalloc]init];

    

    self.headerButton = headerButton;

//    [headerButton setBackgroundColor:[UIColor redColor]];

    

    /**

     设置背景图片

     设置图片的时候,哪些一定要分状态

     title/titleColor image , backgroudImage

     

     button.titleLabel.font  // 所有状态下的文本大小

     */

    [headerButton setBackgroundImage:[UIImageimageNamed:@"buddy_header_bg"]forState:UIControlStateNormal];

    [headerButton setBackgroundImage:[UIImageimageNamed:@"buddy_header_bg_highlighted"]forState:UIControlStateHighlighted];

    

    // 设置图片

    [headerButton setImage:[UIImageimageNamed:@"buddy_header_arrow"]forState:UIControlStateNormal];

    

    // title 设置颜色

    [headerButton setTitleColor:[UIColorblackColor]forState:UIControlStateNormal];

    

    // 设置button的水平对其方式

    headerButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;

    

    // 设置图片的内边距

    headerButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

    

    // 设置文本的内边距

    headerButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);

    

    /**

     保证buttonimageView在旋转之后保持原有的形状

     UIViewContentModeScaleToFill,  拉伸填充

     UIViewContentModeScaleAspectFit,  自适应

     UIViewContentModeScaleAspectFill,  自适应填充

     UIViewContentModeCenter,   保持原有的尺寸

     */

    

    headerButton.imageView.contentMode =UIViewContentModeCenter;

    

    // clipsToBounds YES; 超出父view的边界的部分将会被剪切掉

    headerButton.imageView.clipsToBounds =NO;

    

    // 为按钮添加点击事件

    [headerButton addTarget:self

                     action:@selector(didLClickButton:)

           forControlEvents:UIControlEventTouchUpInside];

    

   //获取按钮图片和标题

UIImage *image = [btn backgroundImageForState:UIControlStateHighlighted];//获取高亮状态下的图片;

 UIImage *img=btn.currentImage;//获取当前按钮的图片;

NSString *str =[btn titleForState:UIControlStateNormal];//获取正常状态下的按钮标题




        //取消失效状态的按钮图像调整

        self.adjustsImageWhenDisabled =NO;

        

        // 取消高亮状态的按钮图像调整

        self.adjustsImageWhenHighlighted =NO;




0 0