1. 程式人生 > >關於Button中的設定title和image的titleEdgeInsets與imageEdgeInsets

關於Button中的設定title和image的titleEdgeInsets與imageEdgeInsets

1、Btton單單設定一個title loginButton.setTitle(“登入", forState: .Normal) 當給按鈕只設置一個標題的時候,標題titleLabel的父檢視為button,不需要設定titleLabel的frame時,titleLabel會在父檢視中居中自動佈局。 2、Btton單單設定一個image 當圖片的大小大於或等於按鈕大小時,需要考慮到手機的螢幕大小,4s及以下手機會載入1倍圖,5、5s手機會載入2倍圖併除以2,6及以上螢幕手機會載入3倍圖併除以3。這樣被處理後才是圖片的真實大小。 拿到圖片的大小後再根據按鈕的大小進行佈局。當按鈕大小大於圖片大小時設定圖片上下會居中顯示,左右會靠左顯示。當按鈕大小小於圖片大小時,如果按鈕寬小於圖片寬、按鈕高大於圖片高,圖片顯示的效果是寬被擠壓,高不變,明顯圖片顯示會變形。所以設定按鈕時要和UED溝通好圖片的大小設定進行標準統一。
3、Btton同時設定Title和Image UIButton同時設定Title和Image後,預設是圖片在左文字在右。 當設定圖片的imageEdgeInsets時,上下是指要移動多少個畫素,左右是指距離左右邊距多少個畫素的一半,也就是說loginButton.imageEdgeInsets=UIEdgeInsetsMake(-10,0, 0,0)意味著圖片在上下佈局中會以之前居中佈局的位置向下移動5個畫素,當設定UIEdgeInsetsMake(-10, 0, 10, 0)時才會向上10個畫素 ----上程式碼(讓我們舉個栗子)
    func shareButtons(){
var button_y : CGFloat = 20
        var buttonWidth :CGFloat =52
        let buttonHeight :CGFloat = buttonWidth +22
        let spacing :CGFloat = ((CMScreenWidth -40) - CGFloat.init(self.buttomImageNames.count) * buttonWidth) / CGFloat.init(self.buttomImageNames.count - 1)
        
        for iin0..<buttomImageNames.count{
            let tempButton =UIButton(type:UIButtonType.Custom)
            tempButton.frame =CGRect.init(x:20 + CGFloat.init(i) * (buttonWidth + spacing) , y:button_y, width: buttonWidth,height: buttonHeight)
            tempButton.setImage(UIImage.init(named:buttomImageNames[i]), forState: .Normal)
            tempButton.setTitle(buttonTitleNames[i], forState: .Normal)
            tempButton.tag = i
            tempButton.addTarget(self, action:#selector(self.shareButtonClickAction(_:)), forControlEvents: .TouchUpInside)
            tempButton.titleLabel?.font =UIFont.init(name:CustomMethod.sharedInstance.fontName(), size:12)
            tempButton.setTitleColor(ColorChange().colorWithHexString(color_4A4A4A), forState: UIControlState.Normal)
            
            let imageWidth = tempButton.imageView!.frame.width
            let imageHeight = tempButton.imageView?.frame.height
            let titleHeight :CGFloat = tempButton.titleLabel!.frame.height
            let imageGap :CGFloat =fabs((tempButton.frame.width - imageWidth) /2)
            tempButton.imageEdgeInsets =UIEdgeInsetsMake(0, imageGap, titleHeight,0)
            tempButton.titleEdgeInsets =UIEdgeInsetsMake(imageHeight! +10, -imageWidth, 0,0)
            
            self.view.addSubview(tempButton)
        }
    }


----上效果圖



 



希望能夠幫助大家~~~