iOS設置button上的文字和圖片上下垂直/水平居中對齊

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];//button的類型  
button.frame = CGRectMake(100, 100,90, 90);//button的frame  
button.backgroundColor = [UIColor cyanColor];//button的背景顏色  

// [button setBackgroundImage:[UIImage imageNamed:@"man_64.png"] forState:UIControlStateNormal];  
      
// 在UIButton中有三個對EdgeInsets的設置:ContentEdgeInsets、titleEdgeInsets、imageEdgeInsets  
[button setImage:[UIImage imageNamed:@"IconHome@2x.png"] forState:UIControlStateNormal];//給button添加image  
button.imageEdgeInsets = UIEdgeInsetsMake(5,13,21,button.titleLabel.bounds.size.width);//設置image在button上的位置(上top,左left,下bottom,右right)這裏能夠寫負值,對上寫-5,那麼image就象上移動5個像素  
      
[button setTitle:@"首頁" forState:UIControlStateNormal];//設置button的title  
button.titleLabel.font = [UIFont systemFontOfSize:16];//title字體大小  
button.titleLabel.textAlignment = NSTextAlignmentCenter;//設置title的字體居中  
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];//設置title在通常狀況下爲白色字體  
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//設置title在button被選中狀況下爲灰色字體  
button.titleEdgeInsets = UIEdgeInsetsMake(71, -button.titleLabel.bounds.size.width-50, 0, 0);//設置title在button上的位置(上top,左left,下bottom,右right)  
      
// [button setContentEdgeInsets:UIEdgeInsetsMake(70, 0, 0, 0)];//  
    
// button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//設置button的內容橫向居中。。設置content是title和image一塊兒變化  
      
[button addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];  

 轉載自:http://www.2cto.com/kf/201311/259154.htmlhtml

相關文章
相關標籤/搜索