iOS Button 上文字圖片位置的設置


    1. 添加圖片+文字/文字+圖片 ,不分前后,圖片默認在文字前邊 加空格隔開
 UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(30, 200, 300, 50)];
    button.backgroundColor =[UIColor grayColor];
    //圖片
    [button setImage:[UIImage imageNamed:@"but"] forState:UIControlStateNormal];
    
    //文字
    [button setTitle:@"  But文字" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font =[UIFont boldSystemFontOfSize:40];
    
    [self.view addSubview:button];

    2.設置文字圖片 顯示整體位置:居中、左、右; 單獨設置文字的位置
    top : 為正數的時候,是往下偏移,為負數的時候往上偏移; 
    left : 為正數的時候往右偏移,為負數的時候往左偏移;
     bottom : 為正數的時候往上偏移,為負數的時候往下偏移;
     right :為正數的時候往左偏移,為負數的時候往右偏移;
 UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(30, 200, 300, 50)];
    button.backgroundColor =[UIColor grayColor];
    //文字
    [button setTitle:@"But文字" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font =[UIFont boldSystemFontOfSize:40];
    //圖片
    [button setImage:[UIImage imageNamed:@"but"] forState:UIControlStateNormal];
    
    /////////////修改///////////////////
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使圖片和文字水平居中顯示
    /*
     UIControlContentHorizontalAlignmentCente
     UIControlContentHorizontalAlignmentLeft
     UIControlContentHorizontalAlignmentRight
     UIControlContentHorizontalAlignmentFill */
    //文字 可以顯示在 button 視圖之外,但不接收點擊事件響應
    [button setTitleEdgeInsets:UIEdgeInsetsMake(button.imageView.frame.size.height ,button.imageView.frame.size.width, 0.0,0.0)];//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變
    ///////////////////////////////////////
    
    
       [self.view addSubview:button];
    
    

 

3.效果:

UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(30, 200, 300, 50)];
    button.backgroundColor =[UIColor grayColor];
    //文字
    [button setTitle:@"But文字" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font =[UIFont boldSystemFontOfSize:40];
    //圖片
    [button setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
    
    /////////////修改///////////////////
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    button.imageEdgeInsets = UIEdgeInsetsMake(0,300-50, 0, 0); //上左下右
//button.titleEdgeInsets = UIEdgeInsetsMake(0,300-50, 0, 0); // 設置文字的位置 上左下右
///////////////////////////////////////  [self.view addSubview:button]; 

 

 

4/  但是圖片尺寸大了  位置會錯亂, 如有遇到的請評論指點

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM