UILabel resize_height_to_fit functionality

I use this code in my apps a LOT to set the height of the frame of a UILabel after setting its text/font/etc. It shoudl auto-calculate the height based on the width and resize the UILabel to fit the text, no matter the font or text length.
This commit is contained in:
Mark Rickert
2015-02-27 11:07:54 -06:00
parent b208bb4721
commit c1e8ef9d0f
2 changed files with 64 additions and 0 deletions

View File

@@ -56,6 +56,17 @@ module RubyMotionQuery
def adjusts_font_size
@view.adjustsFontSizeToFitWidth
end
def resize_height_to_fit
@view.lineBreakMode = UILineBreakModeWordWrap
@view.numberOfLines = 0
attributed_text = NSAttributedString.alloc.initWithString(@view.text, attributes:{NSFontAttributeName => @view.font})
rect = attributed_text.boundingRectWithSize([@view.frame.size.width, Float::MAX], options:NSStringDrawingUsesLineFragmentOrigin, context:nil)
expected_label_size = [@view.frame.size.width, rect.size.height.ceil]
@view.frame = [@view.frame.origin, expected_label_size]
end
end
end

View File

@@ -86,5 +86,58 @@ describe 'stylers/ui_label' do
view.get.lineBreakMode.should == NSLineBreakByTruncatingHead
end
it "should resize height larger when asked" do
view = @vc.rmq.append(@view_klass, :ui_label_kitchen_sink)
view.style do |st|
st.frame = {
w: 200,
h: 5
}
st.text = "Testing this thing with a really long string so that it clips but then will resize to fit properly."
end
old_size = view.get.frame.size
old_size.should == CGSizeMake(200,5)
view.style {|st| st.resize_height_to_fit}
size = view.get.frame.size
size.width.should == 200
size.height.should > 5
size.height.should < Float::MAX
# Set the height to zero and try again
view.style do |st|
st.frame = {
h: 0
}
end
view.style {|st| st.resize_height_to_fit}
view.get.frame.size.height.should > 0
end
it "should resize height smaller when asked" do
view = @vc.rmq.append(@view_klass, :ui_label_kitchen_sink)
view.style do |st|
st.frame = {
w: 150,
h: 5000
}
st.text = "This is a small label."
end
old_size = view.get.frame.size
old_size.should == CGSizeMake(150,5000)
view.style {|st| st.resize_height_to_fit}
size = view.get.frame.size
size.width.should == 150
size.height.should < 5000
size.height.should > 0
end
end