2017-10-17 127 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