viewDidLoad
の中で一度セットしたUIButton
のタイトルをその後変更したいときの方法。
普通にsetTitle:forState:
だけ使ってタイトルを変更すると、アニメーションが入ってボタンのタイトルが一度消えたような(ちらついたような)感じになってしまうので、ちょっとだけコードを加える。
test_view_controller.rb
class TestViewController < UIViewController
def viewDidLoad
super
...
testView = TestView.setContent self
...
self.view.addSubview testView
end
end
test_view.rb
class TestView < UIScrollView
attr_accessor :hogeButton
def setContent(controller)
self.alloc.initWithFrame(controller)
end
def initWithFrame(controller)
super(controller.view.bounds)
...
hogeButton = UIButton.buttonWithType(UIButtonTypeSystem).tap do |b|
...
b.setTitle("hogehoge", forState: UIControlStateNormal)
...
end
self.hogeButton = hogeButton
# ボタンのタイトルを変更
changeButtonTitle
...
end
def changeButtonTitle
Dispatch::Queue.concurrent.async do
...
Dispatch::Queue.main.async do
UIView.setAnimationsEnabled false
self.hogeButton.setTitle("fugafuga", forState: UIControlStateNormal)
self.hogeButton.layoutIfNeeded
UIView.setAnimationsEnabled true
end
end
end
end
タイトル変更時はsetAnimationsEnabled:
でアニメーションをオフにしておく。
さらにlayoutIfNeeded
を呼んでレイアウトを変更する。
これで、ボタンのタイトルの文字の変更が、自然な感じになった。