嗨我試圖讓它選中後的文本的按鈕。 我正在這樣做,以中心的圖像和文本的按鈕。如何在選擇後獲取文本按鈕?
我創建了一個函數來幫助我。我想在選擇按鈕時再次調用它來再次渲染大小,然後再次中心當前文本按鈕的依賴關係。但是,選擇時,我不會在文本中進行任何更改。有人知道我該怎麼做?
override func viewDidLoad() {
super.viewDidLoad()
let button: UIButton = UIButton()
button.frame = CGRectMake(100, 100, 150, 60)
button.setImage(UIImage(named: "img"), forState: .Normal)
button.setImage(UIImage(named: "imgSelected"), forState: .Selected)
button.setTitle("Test", forState: .Normal)
button.setTitle("Prueba", forState: .Selected)
button.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
button.setTitleColor(UIColor.lightGrayColor(), forState: .Selected)
button.addTarget(self, action: #selector(HistoricalViewController.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
//Center the image with text
setupButton(button)
self.view.addSubview(button)
}
func buttonAction(sender:UIButton){
let button = sender as UIButton
if button.selected{
button.selected = false
}else{
button.selected = true
}
print("Current title \(button.currentTitle!)")
setupButton(button)
}
func setupButton(button: UIButton) {
let spacing: CGFloat = 6.0
let imageSize: CGSize = button.imageView!.image!.size
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, -(imageSize.height + spacing), 0.0);
let labelString = NSString(string: button.titleLabel!.text!)
print("button title \(button.titleLabel!.text!)")
let titleSize = labelString.sizeWithAttributes([NSFontAttributeName: button.titleLabel!.font])
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width);
}
編輯:
我更新了我的功能就是這樣,保持圖像的中心
func buttonAction(sender:UIButton){
let button = sender as UIButton
if button.selected{
button.selected = false
button.setTitle("Test", forState: UIControlState.Normal)
}else{
button.selected = true
button.setTitle("Prueba", forState: UIControlState.Normal)
}
setupButton(button)
}
而且
func setupButton(button: UIButton) {
let spacing: CGFloat = 6.0
let imageSize: CGSize = button.imageView!.image!.size
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, -(imageSize.height + spacing), 0.0);
let labelString = NSString(string: button.titleForState(button.selected ? .Selected : .Normal)!)
let titleSize = labelString.sizeWithAttributes([NSFontAttributeName: button.titleLabel!.font])
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width);
}
謝謝!這適用於獲取當前按鈕標題。 – Dasoga