2017-10-17 128 views
1

裏面willWillLayoutSubviews()我打電話UIButton's方法setTileTheme(),我創建。結果可以在下面看到 - 重複UILabel出現在另一個下面。我已經嘗試從viewDidLoad()等嘗試調用我的方法,但它沒有幫助。UIButton內的重複UILabel

有人知道我爲什麼要面對這個問題嗎?

func setTileTheme(image: UIImage, title: String) { 
    self.translatesAutoresizingMaskIntoConstraints = false 
    tintColor = .green 
    backgroundColor = .white 
    setBorder(width: 1.5, color: .lightGray) 
    roundCorners(radius: 5) 
    self.layer.masksToBounds = true 

    let width = self.frame.size.width 
    let height = self.frame.size.height 
    let offset: CGFloat = width/4.5 

    let titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: width, height: 30)) 
    titleLabel.center = CGPoint(x: width/2, y: height-offset) 
    titleLabel.text = title 
    titleLabel.font = titleLabel.font.withSize(15) 
    titleLabel.textAlignment = .center 
    titleLabel.textColor = .darkGray 
    self.insertSubview(titleLabel, at: 0) 

    imageEdgeInsets = UIEdgeInsets(top: height/8, left: width/4, bottom: height*3/8, right: width/4) 
    setImage(image, for: .disabled) 
    setImage(image.withRenderingMode(.alwaysTemplate), for: .normal) 
} 

Result

+0

多少次被稱爲'setTileTheme()'?多次。根據底部標籤的較深顏色,我會說在同一位置有更多顏色。至少總共稱爲3次。所以使用一個屬性來代替'titleLabel'。 – Larme

回答

2

的UIButton已經titleLabel和ImageView的。你在做什麼是你正在創建一個新的標籤,並將其添加到按鈕視圖不會取代默認標籤。

所有你需要的是

override func titleRect(forContentRect contentRect: CGRect) -> CGRect { 
     return CGRectCGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: 30) 
    } 


func setTileTheme(image: UIImage, title: String) { 
      self.translatesAutoresizingMaskIntoConstraints = false 
      tintColor = .green 
      backgroundColor = .white 
      setBorder(width: 1.5, color: .lightGray) 
      roundCorners(radius: 5) 
      self.layer.masksToBounds = true 

      let width = self.frame.size.width 
      let height = self.frame.size.height 
      let offset: CGFloat = width/4.5 

      self.titleLabel?.text = title 
      self.titleLabel?.font = titleLabel.font.withSize(15) 
      self.titleLabel?.textAlignment = .center 
      self.titleLabel?.textColor = .darkGray 

      imageEdgeInsets = UIEdgeInsets(top: height/8, left: width/4, bottom: height*3/8, right: width/4) 
      setImage(image, for: .disabled) 
      setImage(image.withRenderingMode(.alwaysTemplate), for: .normal) 
     } 

我相信你想設置,你可以輕鬆地通過重寫titleRect

編輯設置按鈕本身的默認標題標籤按鈕的標題標籤框架:

我可以看到,你正在嘗試設置嵌入Button的圖像以及。向imageView添加插圖將簡單地在imageView中移動圖像,但imageView框架保持不變。相反如果你想影響的ImageView框架本身,那麼你可以簡單地覆蓋

override func imageRect(forContentRect contentRect: CGRect) -> CGRect { 
    //whatever calculation you wanna provide 
    //for example 
    return CGRect(x: (self.bounds.size.width/2 + 5), y: self.bounds.size.height/2, width: (self.bounds.size.width/2 - 5), height: self.bounds.size.height) 
} 

希望它可以幫助

+0

謝謝!經過一些編輯後,所有東西都像魅力一樣。 – Crunkz

+0

@crunkz:很高興我可以有所幫助:)快樂編碼:) –

+1

非常感謝! – Crunkz