A control that executes your custom code in response to user interactions.
Programmatically. To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .
//make the buttons content appear in the top-left
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
//move text 10 pixels down and right
[button setTitleEdgeInsets:UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 0.0f)];
And in Swift
//make the buttons content appear in the top-left
button.contentHorizontalAlignment = .Left
button.contentVerticalAlignment = .Top
//move text 10 pixels down and right
button.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 0.0, 0.0)
Swift 5
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)
The easiest way to do it visually is to use the attribute inspector** (appears when editing a xib/storyboard), setting the "edge" property to title, adjusting it's insets, then setting "edge" property to image, and adjusting accordingly. It's usually better than coding it , since it's easier to maintain and highly visual.
Derive from UIButton and implement the following method:
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
Edit:
@interface PositionTitleButton : UIButton
@property (nonatomic) CGPoint titleOrigin;
@end
@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
contentRect.origin = titleOrigin;
return contentRect;
}
@end
For my projects I've this extension utility:
extension UIButton {
func moveTitle(horizontal hOffset: CGFloat, vertical vOffset: CGFloat) {
self.titleEdgeInsets.left += hOffset
self.titleEdgeInsets.top += vOffset
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With